简体   繁体   中英

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.

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. Consider a simple class

public class HelloWorld {
    String data;
}

If you generate hashCode() and equals() you will see this general pattern followed. 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. 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.

Update : As Tim has suggested 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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