The strange problem of the == judgment of two Integer objects in Java due to automatic boxing

Integer is a wrapper class of int. Since it is a class, when a variable of Integer type is == compared, it is to judge whether the addresses referenced by two objects are the same.
Therefore, the return value of the following code is false

public static void main(String[] args) {
    
    
        Integer i1 = new Integer(1);
        Integer i2 = new Integer(1);
        System.out.println(i1 == i2);//false
    }

This is easier to understand, because every new operation will apply for a new object in the heap space. Their addresses must be different.
But what about the result of the following code?

public static void main(String[] args) {
    
    
        Integer i1 = 1;
        Integer i2 = 1;
        System.out.println(i1 == i2);//true
    }

The result of this code turned out to be True.
1 is an int type, it will be automatically boxed into an Integer, which is equivalent to

public static void main(String[] args) {
    
    
        Integer i1 = Integer.valueOf(1);
        Integer i2 = Integer.valueOf(1);
        System.out.println(i1 == i2);//true
    }

But this does not seem to explain why the addresses referenced by i1 and i2 are the same.
Don't worry and look down

public static void main(String[] args) {
    
    
        //Integer i1 = Integer.valueOf(128);
        //Integer i2 = Integer.valueOf(128);
        Integer i1 = 128;
        Integer i2 = 128;
        System.out.println(i1 == i2);//false
    }

what! ? The return value of this code turned out to be False.
So what is causing this.
First of all, we know that when int is assigned to Integer, it will be automatically boxed into Integer
, that is, the following two lines of code are equivalent

 		Integer i1 = Integer.valueOf(128);
        Integer i1 = 128;

Then we open the source code of Integer.valueOf()

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

What is IntegerCache.low among them?
Insert picture description here

At this point, the mystery is revealed. It turns out that Integer has already cached the numbers from -128 to 127 for us. If we call the Integer.valueOf() method, we will determine whether the passed parameter is within this range. If so, it returns the cached Integer object.
Other packaging classes also have similar caching mechanisms.
Therefore, when judging whether the packaging classes are equal, it is best to use the equals() method instead of == (Of course the Boolean type does not matter, because it has only two possibilities, and these two have already been cached)

Guess you like

Origin blog.csdn.net/qq_30033509/article/details/115052402