java on Integer initialization

code segment

public class Test03 {


    public static void main(String[] args) {

        Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;


        System. out.println( f1 == f2); //true
        System. out.println( f3 == f4); //false
    }
}

When we assign an Integer to an int type, the Integer's static method valueOf is called.

Integer f1 = Integer.valueOf(100); 
Integer f2 = Integer.valueOf(100); 
Integer f3 = Integer.valueOf(150); 
Integer f4 = Integer.valueOf(150); 

Thinking: So is the Integer returned by Integer.valueOf() created by new Integer(num);? If this is the case, then == comparisons will both return false because they refer to different heap addresses.
Specifically look at 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);
}

The cache array in IntegerCache is initialized as follows, and the value of -128 - 127 is stored

cache = new Integer[(high - low) + 1];
int j = low;
for( int k = 0; k < cache.length ; k ++)
    cache[k] =
    cache[k] = new Integer(j ++);

From the above, we can know that when the int value assigned to Interger is -128 - 127, it is directly obtained from the cache. These cache references are unchanged to the address of the Integer object, but for numbers that are not in this range, new Integer(i ) This address is a new address and cannot be the same.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324832264&siteId=291194637