Why does the comparison of different objects return true?

2

First code:

Integer i1 = 1234;
Integer i2 = 1234;
System.out.println(i1 == i2); //false
System.out.println(i1.equals(i2)); //true

Although it seems that primitive types are being used, they are actually objects, so when these objects are compared using == the result is false , since they are different instances of Integer . So far so good.

Second code:

Integer i1 = 123;
Integer i2 = 123;
System.out.println(i1 == i2); //true
System.out.println(i1.equals(i2)); //true

Why is the result of the first comparison being true and not false as in the first code?

    
asked by anonymous 21.02.2017 / 22:38

2 answers

6

Because of interning Flyweight pattern >. This technique is often perceived as a cache , and is even in a way, but the main advantage is sharing the state. Traditional cache has a slightly different concept, it can be invalidated, has restricted lifetime.

Java has decided that small numbers should have this share because the object has a very high cost. A Integer has more than 20 bytes of consumption. Probably if I did not need an object in those cases (Java 10 will have mechanism that allows to avoid expensive objects for small data, but came a little late, has a very large code base using the objects).

Objects that contain a value that fits in 1 byte is already represented in the code by interning , so all 123 numbers in objects (not to be confused with primitives like int ) will be in the same memory location.

You may wonder why not do with objects that need 2 or 4 bytes. Only the 2-byte would need at least 128KB (in practice it should go over 1MB), it does not usually compensate.

    
21.02.2017 / 23:17
3

Java, to save memory, keeps a cache of some objects, and every time a boxing is done it reuses them.

The following objects are cached:

  • All Boolean and Byte ;
  • Short and Integer from -128 to 127;
  • % with% ASCII, such as letters, numbers, etc;

So, in the second code, the object really is the same, because it is an Integer, within the range of the cache.

More details on documentation .

    
21.02.2017 / 22:45