其他分享
首页 > 其他分享> > 拆箱与装箱的一些注意事项(Integer -128~127 的恩怨)

拆箱与装箱的一些注意事项(Integer -128~127 的恩怨)

作者:互联网

public class Main {

    public static void main(String[] args) {               Integer a = 100;             Integer b = 100;             Integer c = 128;             Integer d = 128;               System.out.println(a==b);             System.out.println(c==d);     } }  

输出:  true

     false

原因:

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

可以看到当不满足if语句中的条件,就会重新创建一个对象返回,那结果必然不相等。继续打开IntegerCache可以看到

private static class IntegerCache {       static final int low = -128;        static final int high;       static final Integer cache[];         static {           // high value may be configured by property           int h = 127;           String integerCacheHighPropValue =               sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");           if (integerCacheHighPropValue != null) {               try {                   int i = parseInt(integerCacheHighPropValue);                   i = Math.max(i, 127);                   // Maximum array size is Integer.MAX_VALUE                   h = Math.min(i, Integer.MAX_VALUE - (-low) -1);               catch( NumberFormatException nfe) {                   // If the property cannot be parsed into an int, ignore it.               }           }           high = h;             cache = new Integer[(high - low) + 1];           int j = low;           for(int k = 0; k < cache.length; k++)               cache[k] = new Integer(j++);             // range [-128, 127] must be interned (JLS7 5.1.7)           assert IntegerCache.high >= 127;       }         private IntegerCache() {}   }

在通过valueOf方法创建Integer对象的时候,如果数值在[-128,127]之间,便返回指向IntegerCache.cache中已经存在的对象的引用;否则创建一个新的Integer对象。所以上面代码中ab相等,cd不相等。

标签:拆箱,int,cache,static,IntegerCache,127,128,Integer
来源: https://www.cnblogs.com/JNU-Iot-Longxin/p/15250892.html