Java cache and equality

I read through java caches for the class, and I'm not quite 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 refer to different objects, but why do they become equal after ++?

+4
source share
2 answers

After the increment, they are reinstalled using Integer.valueOf() and for small absolute values ​​(between -128 and 127 by default), which uses cached instances.

+5
source

The key word here is integer caching. Integer values ​​under 128 * are cached, and ++ returns the result of interning valueOf .

There are two fun experiments you can perform to understand how Integers caching works:

  • Replace new Integer(2) with Integer.valueOf(2) and immediately notice that x==y
  • Replace 2 with 200 and note that x++ and y++ return different objects

<h / "> * It is possible to control this: java.lang.Integer.IntegerCache.high=high_val

+4
source

Source: https://habr.com/ru/post/1443342/


All Articles