先看以下两个面试题的输出结果
题1
public class IntAndInteger {
public static void main(String[] args) {
Integer a = new Integer(1);
int b = 1;
Integer c = 1;
System.out.println(a == b); //true a自动拆箱成int,然后再和b比较
System.out.println(a == c); //false 两个引用不是指向同一个引用对象
}
}
题2
public class IntAndInteger {
public static void main(String[] args) {
Integer a = 1, b = 1;
Integer c = 128,d = 128;
System.out.println(a == b); //true
System.out.println(c == d); //false
}
}
注:== 对于基本类型,比较的是数值的大小,对于引用类型,则比较的两个引用对象的内存地址值。
分析
题1
a == b返回true,因为a自动拆箱成int,然后和b比较。 1==1,返回true。
Java是一个近乎纯洁的面向对象编程语言,但是为了编程的方便还是引入了基本数据类型,但是为了能够将这些基本数据类型当成对象操作,Java为每一个基本数据类型都引入了对应的包装类型(wrapper class),int的包装类就是Integer,从Java 5开始引入了自动装箱/拆箱机制,使得二者可以相互转换。
Java 为每个原始类型提供了包装类型:
- 原始类型: boolean,char,byte,short,int,long,float,double
- 包装类型:Boolean,Character,Byte,Short,Integer,Long,Float,Double
题2
Integer a = 1;
当我们给一个Integer对象赋一个int值的时候,会调用Integer类的静态方法valueOf,下面分析一下valueOf的源码
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
这其中的IntegerCache是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() {}
}
由以上代码可知如果整型字面量的值在-128到127之间,那么不会new新的Integer对象,而是直接引用常量池中的Integer对象。
int和Integer
int 是JAVA八个基本类型中的一个,它的值范围为 2147483648~2147483647,占用4个字节,32位
Integer 是引用类型,包装了基本类型中的int
int的初始化可以是 int a = 1,而 Integer的初始化可以是 Integer a = 1 或者 Integer a = new Integer(1)
Integer 缓存了 -128~127 范围数值在内部的一个数组内,该数值范围可以通过启动虚拟机参数 -XX:AutoBoxCacheMax= 进行设置大小 并且在该范围内用==比较另外一个Integer的时候,实际上是int类型的比较,不过不推荐该方式,包装类型尽量使用equals来进行比较。