在 java 的自动装箱中,存在一个 128 陷阱, 先看一段 代码 :
public static void main(String[] args) {
Integer a = 127 ;
Integer b = 127 ;
Integer c = 128 ;
Integer d = 128 ;
Integer cc = 1000 ;
Integer dd = 1000 ;
System.out.println(( a == b ));
System.out.println(( c == d ));
System.out.println(( cc == dd ));
System.out.println("----------------");
System.out.println( (a.equals( b )) );
System.out.println( (c.equals( d )) );
System.out.println( (cc.equals( dd )) );
}
执行结果是 :
首先知道 Integer 是包装类 , a , b 等是包装类的对象 , " == " 号比较的是对象的地址是否一致 , 一致时返回 true ,否则返回 false .
equals () 方法是 Integer 重写的方法, 当数值一致时 返回 true , 否则返回 false .
导致 127 和 128 分界出结果不相等原因在于 自动装箱时存在一定规范 :
对于 自动装箱规范要求 : boolean , byte , char <= 127 , 介于 -128 ~ 127 之间的 short 和 int 被包装到固定的对象中 .
所以当 Integer a = 127 , Integer b = 127 时 , a 和 b 被包装到同一个对象中 , 所以 用 == 号判断时, 认为是相等的. 而当等于
128 时,则是分装在两个对象中的 , 自然地址也不会相等 , 所以 == 号 判断结果为 false . 超过128 结果也是一样的 .
这就是所谓的 "128陷阱" .
所以在比较两个包装类的对象时, 尽量使用 equals 方法 ,这样可以得到你想要的结果 , 使用 == 号容易导致 128陷阱 .