String与Long类型比较的陷阱 博客分类: codes
程序员文章站
2024-02-12 20:03:40
...
public class LongTest { public static void main(String[] args) { Long tt = 0l; System.out.println(tt); boolean flag = "0".equals(tt); boolean flag1 = "0".equals(tt.toString()); System.out.println(flag); System.out.println(flag1); } }
输出结果:
0
false
true
boolean flag = "0".equals(tt);
分析:
在这段代码中tt为Long类型,不同类型对象比较永远返回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; }