Search code examples
javahashmapassignment-operator

Node.equals method in java.utils.HashMap


The static class Node in Hashmap has an equals method to compare this Node object with a Node object passed as a parameter.

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}

Have a look at the line where object o is assigned to a new Map.Entry object e. The key and value comparison could have been done with object o itself. Why is it first copied to object e and then compared? The object o is not getting modified in any way.


Solution

  • The line Map.Entry<?,?> e = (Map.Entry<?,?>)o; does not assigned to a new Map.Entry object, it only casts o to an Entry object, to be allowed to use getKey() and getValue() methods required to compare with the current Entry object

    The only methods available on o are detailed here java.lang.Object