关于Integer和int的对象比较(拆箱)

我们知道Integer的数据能够自动拆箱为int,int的数据能够自动装箱成Integer,但在实际使用的时候,会存在很多陷阱;下面直接看代码:

package jvm;

public class CompileDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Integer a = 1;
		Integer b = 2;
		Integer c = 3;
		Integer d = 3;
		Integer e = 321;
		Integer f = 321;
		Long g = 3L;
	    int k = 1;
        Integer m = 194;
	    Integer n = 127;
		System.out.println(c == d);
		System.out.println(c.equals(d));
		System.out.println(e == f);
		System.out.println(c == (a +b));
		System.out.println(c.equals(a + b));
		System.out.println(g == (a + b));
		System.out.println(g.equals(a+b));	
		System.out.println(a == k);
        System.out.println(f == (m + n));
	}

}
执行结果如下:
true
true
false
false
false
true
false
true
true

结果分析:

1. Integer c=3和Integer d=3为true ,而Integer e=321和Integer f=321为false 

   解释:  这是因为Integer作为常量时,对于-128到127之间的数,会进行缓存,也就是说Integer c=3时,在范围之内,这个时候就存放在缓存中,当再创建d时,java发现缓存中存在3这个数了,就直接取出来赋值给d,所以c== d。当超过范围时,就new Integer()来new一个对象了,所以e、f 都是new Integer(321)出来的变量,所以它们不等。

2. Integer a = 1和Int k=1 为true,当Integer和int比较时,会自动拆箱成int.

3.c.equals(d) 为true,同1的解释;

4.c.equals(a + b)为true,而g.equals(a+b)为false,根据原则:包装类的“==”运算在不遇到算术运算的情况下不会自动拆箱,以及equals()方法不处理数据转型的关系;

   a+b:会自动拆箱(这个跟>127是否缓存没有关系,从f == (m + n)为true也可以看出来)

   g.equals(a+b):类型不一致

猜你喜欢

转载自blog.csdn.net/u010020099/article/details/81981299