Java中Interger包装类的IntegerCache

 1 public void method1() {
 2 Integer i = new Integer(1);
 3 Integer j = new Integer(1);
 4 System.out.println(i == j);
 5 Integer m = 1;
 6 Integer n = 1;
 7 System.out.println(m == n);//
 8 Integer x = 128;
 9 Integer y = 128;
10 System.out.println(x == y);//
11 }

上述方法第4行输出false:因为 i 和 j 都是引用数据类型,==操作符两边为引用数据类型则判断两个引用数据类型变量是否指向同一个对象,显然,这里new了两个对象,故为false。

第7行输出为true:Integer类中定义了一个IntegerCache,源码如下:

 1 private static class IntegerCache {
 2         static final int low = -128;
 3         static final int high;
 4         static final Integer cache[];
 5 
 6         static {
 7             // high value may be configured by property
 8             int h = 127;
 9             String integerCacheHighPropValue =
10                 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
11             if (integerCacheHighPropValue != null) {
12                 try {
13                     int i = parseInt(integerCacheHighPropValue);
14                     i = Math.max(i, 127);
15                     // Maximum array size is Integer.MAX_VALUE
16                     h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
17                 } catch( NumberFormatException nfe) {
18                     // If the property cannot be parsed into an int, ignore it.
19                 }
20             }
21             high = h;
22 
23             cache = new Integer[(high - low) + 1];
24             int j = low;
25             for(int k = 0; k < cache.length; k++)
26                 cache[k] = new Integer(j++);
27 
28             // range [-128, 127] must be interned (JLS7 5.1.7)
29             assert IntegerCache.high >= 127;
30         }
31 
32         private IntegerCache() {}
33     }

该IntegerCache中定义了一个Integer数组,数组保存了值为-128~127的Integer对象,若自动装箱的基本数据类型在[-128, 127]中,则直接指向数组中的该元素,否则需要重新new一个新Integer对象装箱。这样做可以使得常用的自动装箱操作不用频繁的new对象,提高代码效率。

依据上述分析,第10行输出的为fasle。

posted @ 2021-09-11 15:09  凸云  阅读(68)  评论(0)    收藏  举报

谢谢打赏!