Integer Cache (take you off pit)

Integer Cache

Ado -----> directly on the code:

public class IntegerDemo {
    public static void main(String[] args) {
        Integer numA = 127;
        Integer numB = 127;
​
        Integer numC = 128;
        Integer numD = 128;
​
        System.out.println("numA == numB : "+ (numA == numB));
        System.out.println("numC == numD : "+ (numC == numD));
    }
}

result:

numA == numB : true
numC == numD : false

      What? How this output with the previous cognitive differ from it? In our code "Integer numA = 127", the compiler will basic data "autoboxing" (Autoboxing) into the packaging, this line is equivalent to "Integer numA = Integer.valueOf (127)" , so we can enter the valueOf method to see its implementation principle.

 Integer类的源码
  
  private static class IntegerCache {
        static final int low = -128;
        static final int high = 127;
        static final Integer cache[];
  ......
  }
  
  public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
 }

 

The source can be seen from the above, valueOf method first determines whether the parameter passed in IntegerCache between the low and high, and if so returns inside the cache array cached value, then it is not a new Integer (i) returns.

----------------------------------------------------------------------------------------------------------------------------------------

Then we go down to watch what IntegerCache, it is Integer internal static class, low default is -128, the default value of 127 high, but high by JVM startup parameters XX: AutoBoxCacheMax = size modifies (as shown), if we according to such a modification, and then execute the above code again, this time the secondary output is true, because the cache section into a 200 -128.

 

Guess you like

Origin www.cnblogs.com/pingping-joe/p/10986261.html