本文参考:http://www.cnblogs.com/dolphin0520/p/3780005.html
装箱 int -》integer,integer ainteger =1;反编译后的实际上是Integer.valueOf(1)
拆箱 integer-〉int,int a = ainteger;反编译后实际上是ainteger.intValue();
规则:
1.== 两边的类型是包装类型,比较的是是否是同一个对象,比较的是地址。
2. == 有1边的数据是基本数据类型,比较的是数值、
3. a+b 等算数运算会触发拆箱操作
4.equals 会触发装箱操作
依据这些看例子
Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
Long g = 3L;
Long h = 2L;
System.out.println(c==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(g.equals(a+h));
需要注意一下的是倒数第二个结果是false。这里看下long的equlas源码可知,传过来的对象不是long类型的直接返回false,因此long.equals(integer)返回false。
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}
这些反编译后的代码为:
package com.my.java.base;
import java.io.PrintStream;
public class TestMZhuangChaiXiang
{
public TestMZhuangChaiXiang() {}
public static void main(String[] paramArrayOfString)
{
Integer localInteger1 = Integer.valueOf(1);
Integer localInteger2 = Integer.valueOf(2);
Integer localInteger3 = Integer.valueOf(3);
Integer localInteger4 = Integer.valueOf(3);
Integer localInteger5 = Integer.valueOf(321);
Integer localInteger6 = Integer.valueOf(321);
Long localLong1 = Long.valueOf(3L);
Long localLong2 = Long.valueOf(2L);
System.out.println(localInteger3 == localInteger4);
System.out.println(localInteger5 == localInteger6);
System.out.println(localInteger3.intValue() == localInteger1.intValue() + localInteger2.intValue());
System.out.println(localInteger3.equals(Integer.valueOf(localInteger1.intValue() + localInteger2.intValue())));
System.out.println(localLong1.longValue() == localInteger1.intValue() + localInteger2.intValue());
System.out.println(localLong1.equals(Integer.valueOf(localInteger1.intValue() + localInteger2.intValue())));
System.out.println(localLong1.equals(Long.valueOf(localInteger1.intValue() + localLong2.longValue())));
}
}