Why does comparing different objects return true?

Asked

Viewed 118 times

4

First code:

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

Even though 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 the result of the first comparison is true and not false as in the first code?

2 answers

11


Because of the interning (Flyweight Pattern). This technique is usually perceived as a cache, And it’s 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 lifespan.

Java 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 you didn’t need an object in these cases (Java 1x now has a mechanism that allows you to avoid expensive objects for small data, but it came a little late, has a very large code base using the objects).

Objects containing a value of 1 byte are already represented in the code by interning, then all the numbers 123 in objects (not to be confused with primitive, as is the int) will be in the same memory position.

You may wonder why not do with objects that need 2 or 4 bytes. Only the 2-byte one would need at least 128KB (in practice it should exceed 1MB), not usually compensate since most will not be used.

Entering the field of opinion is that this should not be done, but until I understand that it fixes a little the problem that should not exist, should not use objects of more than 20 bytes to store such trivial information, or even objects should not occupy so much space, what would not solve but already help the problem.

7

Java, to save memory, maintains a cache of some objects, and every time a Boxing is made (transformation of primitives into Wrappers) he reuses them.

The following objects are kept in the cache:

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

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

More details on documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.