不同类型的对象比较不相等(字符串与包装类比较)
程序员文章站
2022-05-09 22:21:09
...
public class LongCompareStringTest { public static void main(String[] args) { Long data = 0l; System.out.println(data.toString()); if ("0".equals(data)) { // 得到false1 System.out.println("true1"); } else { System.out.println("false1"); } if (0l == data) { // 得到true2 System.out.println("true2"); } else { System.out.println("false2"); } } }
调用equals方法时,首先判断实例类型,不同实例,直接返回false
String#equals
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String) anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }