int和integer的区别:
- int是基本数据类型,Iteger是int的包装类(是一个对象)。
- Integer可能会创建一个新的空间,但int只是将数据存储在内存空间中。
- Integer和int不是同一种类型,但都可以声明数据。
- Integer的初始值是null,但int的初始值是0。
int和integer的一些使用:
- Iteger使用new去声明同样的数据,把他们进行比较得到的是false,虽然int不能用new的方式进行比较但用int方法声明的变量进行比较得到是true。(因为通过new方法生成了两个对象他们的地址是不相同的)
public static void main(String[] args) {
int a=9;
int b=9;
System.out.println(a==b);//true
Integer aa=new Integer(9);
Integer bb=new Integer(9);
System.out.println(aa==bb);//false
}
- 如果我们将相同数据int类型的数和Integer类型的数进行比较,不管是否通过new方法,得到的结果都是true。(因为Integer在和int比较时会调用一个intValue()的方法将返回一个int类型的数)
int a=9;
Integer bb=new Integer(9);
System.out.println(a==bb);//true
- 对于两个非new生成的Integer对象,进行比较时,如果两个变量的值在区间-128到127之间,则比较结果为true,如果两个变量的值不在此区间,则比较结果为false。(因为在-128到127之间的数已经被提前声明,再声明直接让变量指向就可以了,而如果超过这个区间那就需要调用new方法重新声明一个)
Integer aa=new Integer(128);
Integer bb=new Integer(128);
System.out.println(aa==bb);//false
Integer的装箱和封箱
装箱
Integer b=Integer.valueOf(2);
valueOf源码
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
IntegerCache源码(建议新手不要看,因为你看了也看不懂)
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() {}
}
装箱也就是把一个int类型的数通过封装变成一个Integer类型的数据。
封箱
System.out.println(b.intValue());
intValue源码
public int intValue() {
return value;
}
封箱就是把Integer类型的数变成int类型的数据。
[1]https://blog.youkuaiyun.com/babycan5/article/details/81942230
[2]https://www.cnblogs.com/guodongdidi/p/6953217.html
[3]https://blog.youkuaiyun.com/sunhuaqiang1/article/details/51958714