简体   繁体   English

为什么Hashtable的equals方法测试值是否为null的情况

[英]Why Hashtable's equals method test the situation that value is null or not

I am reading the Hashtable's code, and I learned that both Hashtable's key and value can not be null, but its 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;
}

It is kind of a pattern that is followed throughout to handle the NPE. 这是一种始终遵循的处理NPE的模式。 Consider a simple class 考虑一个简单的类

public class HelloWorld {
    String data;
}

If you generate hashCode() and equals() you will see this general pattern followed. 如果生成hashCode()和equals(),则会看到此常规模式。 As in this case 在这种情况下

@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;
}

As you can see we always check for null. 如您所见,我们总是检查null。 It is not mandatory but a good programming practice. 这不是强制性的,而是一种好的编程习惯。 I understand it makes no sense in the case of Hashtable's but as I mentioned earlier developers must have added this check to maintain a uniform pattern. 我了解在Hashtable的情况下没有任何意义,但是正如我之前提到的,开发人员必须添加此检查以保持统一的模式。

Update : As Tim has suggested Since Hashtable is subclassable, it is possible for a subclass to try to support null keys or values . 更新 :正如Tim所建议的那样, Since Hashtable is subclassable, it is possible for a subclass to try to support null keys or values So it is safe to do a null check. 因此,进行null检查是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM