Java 空检查为什么使用 == 而不是 .equals()
在Java中,我被告知在进行空检查时,应该使用==而不是.equals()。这是什么原因?
在Java中,我被告知在进行空检查时,应该使用==而不是.equals()。这是什么原因?
它们是两个完全不同的东西。 比较变量包含的对象引用(如果有)。 检查两个对象是否根据其合约是否相等,以了解相等的含义。两个不同的对象实例完全有可能根据其协定“相等”。然后是一个小细节,因为这是一个方法,如果你尝试在引用上调用它,你会得到一个.==
.equals()
equals
null
NullPointerException
例如:
class Foo {
private int data;
Foo(int d) {
this.data = d;
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != this.getClass()) {
return false;
}
return ((Foo)other).data == this.data;
}
/* In a real class, you'd override `hashCode` here as well */
}
Foo f1 = new Foo(5);
Foo f2 = new Foo(5);
System.out.println(f1 == f2);
// outputs false, they're distinct object instances
System.out.println(f1.equals(f2));
// outputs true, they're "equal" according to their definition
Foo f3 = null;
System.out.println(f3 == null);
// outputs true, `f3` doesn't have any object reference assigned to it
System.out.println(f3.equals(null));
// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anything
System.out.println(f1.equals(f3));
// Outputs false, since `f1` is a valid instance but `f3` is null,
// so one of the first checks inside the `Foo#equals` method will
// disallow the equality because it sees that `other` == null
如果你调用你会得到.equals()
null
NullPointerException
因此,始终建议在调用方法之前检查空性
if(str!=null && str.equals("hi")){
//str contains hi
}
另请参见