Java基础:128陷阱以及对Integer的缓存分析

一、首先介绍一下Integer的缓存实现

在Java 5,对于Integer的操作引入了一个新功能来节省内存和提高性能。Integer是java为int提供的封装类。默认值为null。

适用于整数值区间-128+127。 只适用于自动装箱。使用构造函数创建对象不适用。

下面来介绍一下自动拆箱和自动装箱。

装箱就是自动将基本数据类型转换为包装器类型(引用类型,一种对象)(调用valueOf()方法);拆箱就是 自动将包装器类型转换为基本数据类型(通过调用intValue(),doubleValue()等方法)。

注意:Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的。
  	 Double、Float的valueOf方法的实现是类似的。
为什么Double类的valueOf方法会采用与Integer类的valueOf方法不同的实现?
   因为在某个范围内的整型数值的个数是有限的,而浮点数却不是。

下图是基本数据类型对应的包装器类型:
在这里插入图片描述
Integer的valueOf()方法的源码:

/**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

通过源码我们可以看到,在通过valueOf方法创建Integer对象的时候,如果数值在[low , high]之间,便返回指向IntegerCache.cache中已经存在的对象的引用;否则创建一个新的Integer对象。
通过查看IntegerCache类的源码,我们可以得知low以及high的值:

/**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    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() {}
    }

由源码可知,IntegerCache是Integer类中定义的一个private static的内部类,从以上代码可以看出,在自动装箱的过程中,缓存是通过for循环实现的。

-XX:AutoBoxCacheMax这个参数是设置Integer缓存上限的参数
也就是说  127 这个参数不是固定的,可以被修改。
在Java 6中,可以通过java.lang.Integer.IntegerCache.high设置最大值。

二、128陷阱

通过一段代码我们来解释:

public class Inter{
	public static void main(String[] args){
		int a = 120;
		Integer b = 120;
		
		Integer c = 220;
		Integer d = 220;
		
		System.out.println( a == b );
		System.out.println( c == d );
	}
}

输出结果为:

true
false

接下来我们就来解释一下:
当Integer b= 120 的时候,会调用 Integer 的 valueOf() 方法,返回一个Integer对象,判断值是否在[-128 , 127]之间,如果存在,直接返回引用;不存在,则创建一个新的Integer对象。

System.out.println( a == b );//在这里Integer会自动拆箱成int,进行值的比较,因此为true。
System.out.println( c == d );//c和d的值大于127,分别创建了一个新的对象,c和d 分别指向了不同的对象,因此结果为false

拓展:当然,如果只想比较c和d的值,可以采用Integer中的intValue()方法。

System.out.println( c.intValue() == d.intValue() ); //true

以上便是对128陷阱的解释以及对Integer的缓存分析。

参考博客:
深入剖析Java中的装箱和拆箱

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值