Java null檢查為什么使用==而不是.equals()在Java中,我被告知在進行空檢查時應該使用==而不是.equals()。這是什么原因?
3 回答

隔江千里
TA貢獻1906條經驗 獲得超10個贊
他們是兩個完全不同的東西。==
比較變量包含的對象引用(如果有)。.equals()
檢查兩個對象是否相等,根據他們的契約來確定平等意味著什么。根據合同,兩個不同的對象實例完全可能“相等”。然后有一個小細節(jié),因為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 instancesSystem.out.println(f1.equals(f2));// outputs true, they're "equal" according to their definitionFoo f3 = null;System.out.println(f3 == null);// outputs true, `f3` doesn't have any object reference assigned to itSystem.out.println(f3.equals(null));// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anythingSystem.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

慕娘9325324
TA貢獻1783條經驗 獲得超4個贊
如果你援引.equals()
,null
你就會得到NullPointerException
因此,在調用適用的方法之前,始終建議檢查nullity
if(str!=null && str.equals("hi")){ //str contains hi}

達令說
TA貢獻1821條經驗 獲得超6個贊
從Java 1.7開始,如果你想比較兩個可能為null的對象,我推薦這個函數:
Objects.equals(onePossibleNull, twoPossibleNull)
java.util.Objects
此類包含用于對對象進行操作的靜態(tài)實用程序方法。這些實用程序包括null-safe或null-tolerant方法,用于計算對象的哈希代碼,返回對象的字符串以及比較兩個對象。
自:1.7
添加回答
舉報
0/150
提交
取消