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-128and127by default), that uses the cached instances.