我们知道Integer是包装类型 判断相等使用equals
但是我在程序中使用时,发现:
Integer a = new Integer(200);
System.out.println(a.equals("200"));
输出false,当时很纳闷,equals不是比较值相等么,为什么会是true;
我就去看了下源码,原来是Integer重写了equals方法
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
传入的”200”是个string类型 直接返回false。
public static void main(String[] args) {
Integer aInteger = Integer.valueOf(0);
System.out.println(aInteger.equals(0));
name(1);
}
private static void name(Object a) {
System.out.println(a.getClass());
}
输出:
true
class java.lang.Integer
使用object接收参数时,会自动装箱,将int转换成Integer对象
所以Integer比较使用 Integer.equals(int);
Integer判断相等,到底该用==还是equals:https://www.jianshu.com/p/9cb9c61b0986