This also works ("on my machine"):
Integer a = 128, b = 128;
whereas this will not work:
Integer a = 127, b = 127;
Auto-boxing a int is the syntactic sugar for calling Integer.valueOf(int) . This function uses a cache for values ββfrom -128 to 127 inclusive. It can cache other values, but in my case it is not.
Thus, destination 128 does not have a cache; it creates a new Integer instance with each automatic box operation, and the reference comparison a != b true. Target 127 has a cache, and the resulting Integer objects are the same cache instance. So, the reference comparison a != b is incorrect.
What I really want to note is to beware of comparing links to auto-boxing. A more likely real problem is that you expect a == b true, because they were assigned the same (automatic field) value, you run some unit tests that confirm your expectation, and then your code exits out of action in the wild when some counter exceeds the upper limit of the cache. Funny times!
erickson Sep 27 '13 at 16:16 2013-09-27 16:16
source share