- int是基本类型,默认值为0,Integer是int的对象包装器类,默认值为null。
Boolean,Byte,Character,Double,Float,Integer,Long,Short对应boolean,byte,char,double,float,int,long,short。对象包装器类不可变,一旦构造了包装器就不允许更改在其中的值。对象包装器类是final,因此不能定义子类。
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
ArrayList< Integer> 的效率远远低于ArrayList<int[]> 因为前者需要将每个值包装进入integer对象。
自动装箱和自动拆箱
对于ArrayList< Integer>的元素插入,list.add(3)会自动转化为list.add(Integer.valueOf(3)) ,这种变换就是自动装箱。
对于Integer对int的赋值,int n = list.get(i),会自动转换为 int n = list.get(i).intValue(); 这种操作是自动拆箱。
自动将原始数据类型转换为一个封装类型被称为自动装箱,自动将一个封装类型转换为一个原始数据类型就称为自动拆箱。
Integer n=3;
n++;
这是编译器自动插入一条对象拆箱指令,然后自增运算,最后将结果装箱。
1)
Integer a=new Integer(1000);
Integer b=1000;
if(a==b){
//false
}
b在静态常量池中,new Integer()生成的变量指向堆中新建的对象,内存引用不同。
2)
Integer a=new Integer(1000);
Integer b=new Integer(1000);
if(a==b){
//false
}
new生成两个对象,变量地址永远不相等。
3)
Integer a=1000;
Integer b=1000;
if(a==b){
//false
}
==检测对象是否指向同一个存储区域,因此这种比较一般不会成立。因为两个变量地址不同。因此需要调入equals方法比较两个包装器对象。
4)
Integer a=100;
Integer b=100;
if(a==b){
//true
}
自动装箱规范要求boolean,byte,char<=127,介于-128~127的short和int被包装到固定的对象。Integer a=100->Integer.valueOf(100),会对100这个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.parseInt()