package cn.itcast.demo;
import java.util.Date;
/*
* Integer类的内部有一个IntegerCache缓存类;
* 实际上就是缓存了一个大小为256的Integer数组;
把-128 ~ 127之间的所有Integer对象都提前创建好,缓存在数组中,方便后面使用;
目的是为了提高性能和节约空间;
当定义一个不在-128 ~ 127之间的Integer对象时,会新创建一个Integer对象
*/
public class DateDemo {
public static void main(String[] args) {
Integer i = 10; // -128 ~ 127
Integer i2 = 10;
Integer i3 = 127;
Integer i4 = 127;
Integer i5 = 128;
Integer i6 = 128;
System.out.println(i == i2);// true
System.out.println(i3 == i4);// true
System.out.println(i5 == i6);// false 比较的是两个对象的地址
System.out.println(i5.equals(i6)); //true 比较的是两个对象的内容
}
}
//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) {
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);
}
high = h;
cache = new Integer[(high - low) + 1]; //缓存了一个大小为256的Integer数组
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++); //该数组里面装了256个Integer类型的对象
}
private IntegerCache() {}
}*/
2018.4.15 长沙
-128-127自动装箱时的陷阱
最新推荐文章于 2022-08-07 21:41:53 发布