Strange Wrapper Classes of behavior with == and! =

Possible duplicate:
Weird Java Boxing

Recently, when I read about wrapper classes, I went through this strange case:

Integer i1 = 1000;
Integer i2 = 1000;

if(i1 != i2) System.out.println("different objects");

if(i1 == i2) System.out.println("same object");

What prints:

different objects

and

Integer i1 = 10;
Integer i2 = 10;

if(i1 != i2) System.out.println("different objects");

if(i1 == i2) System.out.println("same object");

What prints:

same object

Is there any reasonable explanation for this case?

thank

+3
source share
3 answers

The reason that ==returns true for the second case is because the primitive values ​​marked with shells are small enough to be interned to the same value at runtime. Therefore they are equal.

In the first case, the Java integer cache is not large enough to contain the number 1000, so you create two different wrapper objects, comparing that the link returns false.

Integer#valueOf(int) ( IntegerCache.high - 127):

public static Integer valueOf(int i) {
    if(i >= -128 && i <= IntegerCache.high)
        return IntegerCache.cache[i + 128];
    else
        return new Integer(i);
}

, .equals(), true, , .

+9

i1 = 1000;

int, i1 == i2 // return true

i1 i2 == test return false

Integer i1 = 10000000;
Integer i2 = 10000000;

if(i1 != i2) System.out.println("different objects"); // true

if(i1 == i2) System.out.println("same object"); // false

:

Integer i1 = 100;
Integer i2 = 100;

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

i1 = 1000000;
i2 = 1000000;

System.out.println(i1 == i2); // false

== . . .equal() , .

Integer i1 = 1000000;
Integer i2 = 1000000;

i1 == i2 // false
i1.equals(i2) // true
+1

, , ,

different objects

, -, .

,

if(i1.equals(i2)) System.out.println("same value");

really prints

same value
-1
source

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


All Articles