【学习笔记】自动封装拆箱
java的基本类型共有8种,由于基本类型的数据不是对象,有是有需要将数据作为对象使用,因此java为其提供了相应的包装类。
byte -> Byte
char -> Character
short -> Short
int -> Integer
long -> Long
float -> Float
double -> Double
boolean -> Boolean
装箱:基本类型数据转换成相对应的包装对象数据
拆箱:将引用类型数据转换为对应的基本类型数据
J2SE5.0提供了自动装箱拆箱,所以一般情况下不需要我们特别注意。
不过,有一些有趣的细节存在:
public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a == b);//true
System.out.println(a == 127);//true
System.out.println(c == d);//false
System.out.println(c == 128);//true
}
在java中,“==”和“!=”对于对象的比较是比较对象引用,而不是值
对于基本类型数据则是比较其值
其中第二跟第四行比较时,进行了自动拆箱,其本身等同于127==127,所以这里第二、第四是正确的
那么这里为什么a==b是对的,而c==d是错的呢
这是因为,在自动封箱时,java在编译时调用Integer.valueOf(num)将值封装,而在该方法中
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
//IntegerCache.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中已经缓存了-128~127的Integer对象,在创建Integer对象时,如果是该范围内的,则直接从该缓存中返回对应对象,否则直接new一个Integer对象。
所以,对于a=b=127,其对于的是同一个对象,而c=d=128则是等同2个不同对象。
说到这,不得不再说另一个案例
public static void main(String[] args) {
Integer a = new Integer(0);
Integer b = new Integer(0);
while(a >= b && a <= b && a != b){
System.out.println("run");
}
}
这是等同一个
while(true)
的死循环,因为当调用new Integer时,会直接生成一个对象,也就是说a与b是属于2个不同的对象,在这>=
与<=
操作,都属于拆箱比较操作,所以该案例条件会成立。