基本数据类型的包装类型比较分为两种类型:
-
相同类型比较
Number
类型比较时,只要有一个调用了拆箱,就可以用“==”
比较,无论是调用intValue
还是longValue
。当然对于包装类的比较,建议使用equals
比较。Integer id1 = 123456789; Integer id2= 123456789; // false System.out.println(id1 == id2); // true System.out.println(id1.longValue() == id2); // true System.out.println(id1.equals(id2));
-
不同类型比较
Number
类型比较时,只要有一个调用了拆箱,就可以用“==”
比较,无论是调用intValue
还是longValue
。如果使用equals
比较,必须要转成相同类型才能正确比较。Long idL = 123456789L; Integer idI = 123456789; // true,注意:Integer转成了Long类型 System.out.println(idL.equals(idI.longValue())); // false,注意:两者类型相同时才能正确比较 System.out.println(idI.equals(idL.longValue())); // true System.out.println(idL == idI.longValue()); System.out.println(idL.intValue() == idI); System.out.println(idI.equals(idL.intValue()));
总结:
- 相同类型的包装类型比较时,建议使用
equals
比较。 - 不同类型的包装类型比较时,建议使用
equals
比较,但是要转成相同的类型!例如:Integer.equals(Long.intValue())
和Long.equals(Integer.longValue())