I've been reading over java caches for class and I'm not exactly sure why this code works.
Integer x = new Integer(2);
Integer y = new Integer(2);
assert x            != y;
assert x.intValue() == y.intValue();
++x;
assert x            != y;
assert x.intValue() != y.intValue();
++y;
assert x            == y;
assert x.intValue() == y.intValue();
I understand that initially x and y are not equal because they reference different objects, but why do they become equal after the ++?
After the increment, they are reboxed using Integer.valueOf(), and for small absolute values (between -128 and 127 by default), that uses the cached instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With