基本数据类型:
byte,short,char,int,long,boolean,double,float
封装类:
Byte,Short,Character,Integer,Long,Boolean,Double,Float
封装类和基本数据类型区别:
1.两者转换过程名称叫做,“拆箱”(intValue())、“装箱”(valueOf(int i))
2.基本数据类型只可以被运算,封装类具有基本数据类型不具有的操作,toString()等等
题目:请输出下面的值并验证
Integer a = 500;
Integer b = 500;
System.out.println(a == b);
System.out.println(a.equals(b));
Integer c = 100;
Integer d = 100;
System.out.println(c == d);
System.out.println(c.equals(d));
Integer e = 127;
Integer f = new Integer(127);
System.out.println(e == f);
Integer h = 128;
int i = 128;
System.out.println(h == i);
验证结果:
答案解析:
1.为什么第一个结果和第三个结果不同,这里需要查看一下Integer封装类中自动装箱的源码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
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() {}
}
其实在初始化之前,Integer类内部就已经完成了一个缓存区的数据存储,有利于内存节省和效率.内部类中已经完成了从
-128到127
的数值的缓存,只要是装箱时是这些数值就可以直接用缓存区中现成的,不需要再新new一个了。所以第三次中两个Integer对象的地址都是指向同一个。2.为什么最后一个是对的?
Integer h = 128;
int i = 128;
System.out.println(h == i);
这里当封装类和基本数据类型进行对比的时候,封装类就会自动拆箱(intValue(){return value;}),最后进行的是基本数据的比较。
上面问题Double,float类型的不行:在某个区间内,整数可以是有限个,但是浮点数是无线个的,所以每次装箱都是新new一个对象.其余类型都和Integer相似。