Integer和int关系以及integer和int的比较
Integer是int的包装类(引用类型),int是基本数据类型。说到包装类我们来梳理一下装箱和拆箱(入门知识,懂得就不用看了)
拆箱:自动拆箱就是包装类型转换成基本数据类型。自动拆箱调用了Integer.intValue(),
装箱:自动装箱就是基本数据类型转换成包装类型。自动装箱过程调用了Integer.ValueOf(int),当int的范围是-128到127,是从Integer常量池中获取的,当超出这个范围是通过new产Integer对象(描述不要到位,具体看下源码)。
例子
Integer m = 9 //自动装箱
int n = m或new Integer(9) //自动拆箱
Integer和int比较时会进行自动拆箱,转化成基本数据类型进行比较,所以Integer和int比较时直接用等号。
Integer a = new Integer(10);
Integer b = new Integer(10);
Integer c = 10;
System.out.println(a == b);//false
System.out.println(a == c);//false
System.out.println(10 == c);//true
记住两个new出来的对象比较是不会相等的,自动装箱的数据是从常量池中获取的也不会和new对象相等
源码
Integer.ValueOf(int)
public static Integer valueOf(int i){
//IntegerCache.low = -128
//IntegerCache.high = 127
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}