java包装类型和基本类型
1. Integer:java Integer会缓存 -128到127的Integer对象,超过此范围则会创建Integger对象
new Integer(123);
new Integer(123) 与 Integer.valueOf(123) 的区别在于:
new Integer(123) 每次都会新建一个对象;
Integer.valueOf(123) 会使用缓存池中的对象,多次调用会取得同一个对象的引用。
编译器会在 自动装箱过程调用 valueOf() 方法。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
下面用valueOf() 对123自动装箱,得到的是缓存池中的对象
Integer m = 123;
Integer n = 123;
System.out.println(m == n); // true
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// 可配置缓存池上限,默认127
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
//Integer 的缓冲池 IntegerCache 很特殊,这个缓冲池的下界是 - 128,上界默认是 127,但是这个上界是可调的,
//在启动 jvm 的时候,通过 -XX: AutoBoxCacheMax= size; 来指定这个缓冲池的大小
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;
}
基本类型对应的缓冲池如下:在使用对应的包装类型时,如果该数值在缓冲池范围内,就可以直接使用缓冲池中的对象。自动装箱用 valueOf()。
boolean values true and false
all byte values
short values between -128 and 127
int values between -128 and 127
char in the range \u0000 to \u007F
2. 使用包装类型的一些注意事项
我们使用集合类时,如 set.add(1000) 则 java会自动 new Integer(1000)放入 set中,因为使用了 valueOf(1000)对1000自动装箱。若放入的值在 [-128,127]中,则放入集合的是 Integer Cache中的对象。
list.add(10000)连续执行两次,则 list.get(0) != list.get(1),因为两次 add操作对 10000自动装箱了两次。而 == 和 !=比较的都是地址。
-
同样若 list.add(100)连续执行两次,则list.get(0)==list.get(1) 为true,因为两次两次自动装箱 valueOf(100)返回的是 Integer Cache中的对象。两个引用指向同一个对象。
-
包装类型和基本类型可以进行自动装箱和拆箱,int可以直接 valueOf() 装箱给 Inteher,Integer也可以直接拆箱给 int。
-
Integer + int = int,即先拆箱,比较也是如此, 如 System.out.println (new Integer(1000)<2000)为true,先拆箱再比较装。
-
(包装类型+基本类型) 的操作都是先拆箱在操作。
-
(包装类型+包装类型) 赋值、比较没问题,和常规操作一样。
-
唯一要注意的是 两个包装类型判断相等不要用 == 号,要用equals, ==号判断的是地址!!!