[英]Why Hashtable's equals method test the situation that value is null or not
我正在閱讀Hashtable的代碼,並且了解到Hashtable的鍵和值都不能為null,但是其equals方法測試了value是否為null的情況。
public synchronized boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<K,V> t = (Map<K,V>) o;
if (t.size() != size())
return false;
try {
Iterator<Map.Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Map.Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) { // Can Hashtable's value be null?
if (!(t.get(key)==null && t.containsKey(key)))
return false;
} else {
if (!value.equals(t.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
這是一種始終遵循的處理NPE的模式。 考慮一個簡單的類
public class HelloWorld {
String data;
}
如果生成hashCode()和equals(),則會看到此常規模式。 在這種情況下
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HelloWorld that = (HelloWorld) o;
if (data != null ? !data.equals(that.data) : that.data != null) return false;
return true;
}
@Override
public int hashCode() {
return data != null ? data.hashCode() : 0;
}
如您所見,我們總是檢查null。 這不是強制性的,而是一種好的編程習慣。 我了解在Hashtable的情況下沒有任何意義,但是正如我之前提到的,開發人員必須添加此檢查以保持統一的模式。
更新 :正如Tim所建議的那樣, Since Hashtable is subclassable, it is possible for a subclass to try to support null keys or values
。 因此,進行null檢查是安全的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.