java包装类比较注意事项:
- 包装类对象直接比较的值是对象地址
- 若要进行value值的比较需要获取真实值,或者直接调用equals方法
code:
@Test
public void basicTest() {
Long t1 = new Long(1L);
Long t2 = new Long(1L);
System.out.println("t1.longValue() == t2.longValue() " + (t1.longValue() == t2.longValue()));
System.out.println("t1 = t2 " + (t1 == t2));
Integer a1 = new Integer(1);
Integer a2 = new Integer(1);
System.out.println("a1 == a2 " + (a1 + a2));
System.out.println("a1.equals(a2) " + (a1.equals(a2)));
String s1 = new String("test");
String s2 = new String("test");
System.out.println("s1 == s2 " + (s1 == s2));
System.out.println("s1.equals(s2) " + (s1.equals(s2)));
}
result:
t1.longValue() == t2.longValue() true
t1 = t2 false
a1 == a2 false
a1.equals(a2) true
s1 == s2 false
s1.equals(s2) true