关于Integer的一些使用细节

自动拆装箱

装箱就是自动将基本数据类型转换为包装器类型;拆箱就是自动将包装器类型转换为基本数据类型。

// 自动装箱
Integer num = 100;
// 自动拆箱
int temp = num;

这个过程是自动执行的,那么我们需要看看它的执行过程
执行上面那句代码的时候,系统为我们执行了:

Integer num = 100; ---> Integer num = Integer.valueOf(100);
int temp = num; ---> int temp = num.intValue();

我们看看Integer.valueOf函数

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

它会首先判断i的大小:如果i小于-128或者大于等于128,就创建一个Integer对象,否则执行IntegerCache.cache[i + 128]。
装箱的过程会创建对应的对象,这个会消耗内存,所以装箱的过程会增加内存的消耗,影响性能。


缓存机制

在 Java 中,== 比较的是对象引用,而 equals 比较的是值。因此,在这个例子中,不同的对象有不同的引用,所以在进行比较的时候都应该返回 false。但是奇怪的是,这里两个相似的 if 条件判断却返回不同的布尔值。

Integer i1 = 9;
Integer i2 = 9;
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i1 == i2); // true
System.out.println(i3 == i4); // false

在JDK5中,为 Integer 的操作引入了一个新的特性,用来节省内存和提高性能。整型对象在内部实现中通过使用相同的对象引用实现了缓存和重用。
上面的规则适用于整数区间 -128 到 +127。
这种 Integer 缓存策略仅在自动装箱(autoboxing)的时候有用,使用构造器创建的 Integer 对象不能被缓存。
同样我们回到之前的Integer.valueOf函数

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

在创建新的 Integer 对象之前会先在 IntegerCache.cache 中查找。有一个专门的 Java 类来负责 Integer 的缓存。
这里我们看看IntegerCache类,它是Integer私有的静态类。

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

在JDK5中,cache的范围是固定的-128到127之间。后来在JDK6之后,最大值映射到 java.lang.Integer.IntegerCache.high,可以使用JVM 的启动参数 -XX:AutoBoxCacheMax=size 修改。是什么原因选择这个 -128 到 127 这个范围呢?因为这个范围的整数值是使用最广泛的。 在程序中第一次使用 Integer 的时候也需要一定的额外时间来初始化这个缓存。

这种缓存行为不仅适用于Integer对象,针对所有整数类型的类都有类似的缓存机制。
对于Double和Float做法就很直接,就是直接创建一个对象,所以每次创建的对象都不一样。

public static Double valueOf(double d) {
    return new Double(d);
}

对于Boolean呢?
内部已经提前创建好两个对象,因为它只有两种情况,这样也是为了避免重复创建太多的对象。

public static final Boolean TRUE = new Boolean(true);

public static final Boolean FALSE = new Boolean(false);

public static Boolean valueOf(boolean b) {
    return (b ? TRUE : FALSE);
}
发布了54 篇原创文章 · 获赞 36 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/XlxfyzsFdblj/article/details/84342559