public class MathUtil { public static boolean compare1(long n1, long n2) { return n1 == n2; } public static boolean compare2(Number n1, Number n2) { if (n1 == null) { return n2 == null; } else { return n1 == n2; } } public static boolean compare3(Number n1, Number n2) { if (n1 == null) { return n2 == null; } else { return n1.longValue() == n2.longValue(); } } public static void main(String[] args) { // 使用long n1== n2 System.out.println(compare1(127, 127L)); // true System.out.println(compare1(127L, 127L)); // true System.out.println(compare1(128L, 128L)); // true // 使用 Long n1== n2 System.out.println(compare2(127, 127L)); // false System.out.println(compare2(127L, 127L)); // true System.out.println(compare2(128L, 128L)); // false // 使用 Long n1.longValue() == n2.longValue(); System.out.println(compare3(127, 127L)); // true System.out.println(compare3(127L, 127L)); // true System.out.println(compare3(128L, 128L)); // true } }
经过验证 ,发现equals 也是可以的
public class MathUtil { public static boolean compare(Number n1, Number n2) { if (n1 == null) { return n2 == null; } else { return n1.equals(n1); } } public static void main(String[] args) { System.out.println(compare(12121L, 12121L)); // true } }
这是前几天系统猛然出现的bug, 当时吓尿了。 后来经过定位;发现 基本数据类型的包装类,对于不在 -128~127 集合外的数字 会不相等;
总结:JAVA中 尽量不用 == , 多使用 equals