int与Integer的区别
-
int是基本类型,Integer是int的包装类型
-
int不需要实例化就能直接使用,Integer需要实例化后才能使用。
-
int是直接存储数据值,而Integer是对象的引用,每当new一个Integer就会产生一个指针来指向此对象
-
int的默认值是0,Integer的默认值是null
例: 在JSP开发中,Integer的默认值为null,所以用el表达式在文本框中显示时,值为空白字符串,而int默认值为0,el表达式显示时值为0,所以。int不适合作为web层的表单数据类型。 -
int不能区分是否赋值,Integer可以区分未赋值及值为0
例:学生成绩管理中,怎么判别一个学生未考试状态及成绩为0?就需要用Integer,而int不能判别,因为int的默认值为0。
int与Integer的延伸比较
1. 当两个new Integer生成的变量进行比较时,结果永远为false。
原因:由于Integer实际上是对一个Integer对象的引用,所以每当new一个Integer对象就会产生一个新的地址值,所以当两个对象进行比较,结果为永远为false。
public static void test1(){
Integer i = new Integer(127);
Integer j = new Integer(127);
System.out.println(i == j);//false
}
2.当一个Integer型变量与一个int型变量进行比较时,只要两个变量值相等,结果为true。
原因:Integer包装类在与基本类型int比较时,Java会自动拆包装为int型进行比较,也就是说实际是两个int型变量在进行比较,所以变量值相等情况下,结果为true。
public static void test2(){
Integer i = new Integer(127);
int j = 127;
System.out.println(i == j);//true
}
3.当一个new Integer生成的变量和一个非new生成的Integer变量进行比较时,结果为false。
原因:new出来的对象指向堆中新创建的对象,非new生成的Integer变量指向java常量池中的对象,二者的内存地址不同,结果为false。
public static void test3(){
Integer i = new Integer(127);
Integer j = 127;
System.out.println(i == j);//false
}
4.当两个非new Integer生成的变量进行比较时,若变量值在[-128~127]之间,结果为true,否则为false。
原因:Integer缓存机制问题,参考本结尾缓存机制的介绍。i、j直接从内存中获取;k、t是重新创建的创建的对象,地址值不一样。
public static void test4(){
Integer i = 127;
Integer j = 127;
System.out.println(i == j);//true
Integer k = 128;
Integer t = 128;
System.out.println(k == t);//false(-128~127)
}
Integer的缓存机制介绍与Integer.valueOf方法
Integer缓存机制源码
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() {}
}
通过源码可以看到,在jvm初始化的时候,数据[-128~127]已经被缓存到了内存中,当调用该范围数据时,直接从内存中调用,不需要新创建一个对象。当超出这个范围后,会重新创建一个对象来存储数据(地址值改变)。
Integer.valueOf方法源码
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
可以看出Integer.valueOf方法也是基于缓存实现,将int型数据包装成Integer类型,范围之内直接获取,范围之外new一个对象出来,减少了对象创建次数节省内存空间。
public static void test5(){
Integer x = Integer.valueOf(127);
Integer y = Integer.valueOf(127);
System.out.println(x == y);//true
Integer w = Integer.valueOf(128);
Integer z = Integer.valueOf(128);
System.out.println(w == z);//false
}