Integer缓冲机制

装箱

将一个 int 的数值,赋值给一个 Integer 引用会触发装箱过程。 int --> Integer : valueOf();

Integer a = 10;		//等价于	Integer a = Integer.valueOf(10);

拆箱

将一个 Integer 的包装类型对象赋值给 int 类型的变量 的过程。 Integer --> int : intValue();

Integer a = 10;	//该语句会触发装箱过程,返回一个 Integer 对象
int b = a;		//将 Integer 类型变量赋值给 int 类型变量,会触发拆箱过程
				//等价于 int b = a.intValue();	直接返回一个 int 的值

缓冲机制

    public static Integer valueOf(int i) {
    	// IntegerCache.low = -128, IntegerCache.high = 127
        if (i >= IntegerCache.low && i <= IntegerCache.high)
        	// cache 是一个存放着值为 -128 到 127 的 Integer 数组
        	//从缓存数组直接取对应的 Integer 对象
            return IntegerCache.cache[i + (-IntegerCache.low)];
        
        //数值不在 [-128, 127] 区间,直接 new 一个 Integer 对象
        return new Integer(i);
    }
    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        //缓存数组,用来存放 -128 到 127 的 Integer 对象
        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 = 127
            high = h;

			// 创建一个大小为 256 的 Integer 对象数组
            cache = new Integer[(high - low) + 1];
            // low = -128
            int j = low;
            // 从 -128 开始到 127 结束,每个数值创建一个 Integer 对象,并把该对象放置到 cache 数组中
            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() {}
    }

测试

Integer a=127;
Integer b=127;
Integer c=128;
Integer d=128;
Integer e = new Integer(10);
Integer f = new Integer(10);
System.out.println(a==b);//返回true;
System.out.println(c==d);//返回false;
System.out.println(e==f);//返回false;

System.out.println(a.equals(b));//返回true;
System.out.println(c.equals(d));//返回true;
System.out.println(e.equals(f));//返回true;
posted @ 2022-05-26 10:56  性感的章鱼哥  阅读(44)  评论(0)    收藏  举报