下面是一道面试题:
package Test05;
public class Demo02 {
public static void main(String[] args) {
Integer a1=59;//1
int a2=59;//2
Integer a3=Integer.valueOf(59);//3
Integer a4=new Integer(59);//4
System.out.println(a1==a2);
System.out.println(a1==a3);
System.out.println(a3==a4);
System.out.println(a2==a4);
}
}
结果为:
true
true
false
true
解析:
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];//5
}
return new Integer(i);
}
private static class IntegerCache {
private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}
当执行语句1时,会执行valueOf()函数,因为-128<=i<=127,所以会执行语句5,由于第一次使用,cache数组为空,所以会初始化一个Integer类型的cache数组范围为-128,127,最终返回的是一个Integer类型的值,
当执行语句2时,这是一个基本数据类型,所以存储在栈中。
当执行语句3时,也会执行valueOf()函数,因为此时cache数组中有值,
所以会直接返回一个该值的引用。
当执行语句4时,是直接重新创建了一个对象,
所以当执行a1==a2时,由于a2为int值,所以a1回自动拆箱变成int,然后进行值比较,为真。
当执行a1==a3,因为a3返回的是a1的引用,所以为真。
当执行a3==a4的时候,它们是不同的对象,结果为假
当执行a2==a4的时候,由于a2为int值,所以a4回自动拆箱变成int,然后进行值比较,为真。
package Test05;
public class Demo02 {
public static void main(String[] args) {
Integer a1=200;
int a2=200;
Integer a3=Integer.valueOf(200);
Integer a4=new Integer(200);
System.out.println(a1==a2);//a1自动拆箱与a2进行值比较,true
System.out.println(a1==a3);//由于大于127小于-128,所以a1,a3是两个对象,false
System.out.println(a3==a4);//a3,a4也是两个对象,false
System.out.println(a2==a4);//a4自动拆箱与a2进行值比较,true
}
}
结果为:
true
false
false
true