0

I can see static Entry class in Hashmap in java have Equals and Hashcode methods.What is the purpose of these methods.put,get methods we use object hashcode and equals methods....

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

    /**
     * Creates new entry.
     */
    Entry(int h, K k, V v, Entry<K,V> n) {
        value = v;
        next = n;
        key = k;
        hash = h;
    }

    public final boolean equals(Object o) {
        if (!(o instanceof Map.Entry))
            return false;
        Map.Entry e = (Map.Entry)o;
        Object k1 = getKey();
        Object k2 = e.getKey();
        if (k1 == k2 || (k1 != null && k1.equals(k2))) {
            Object v1 = getValue();
            Object v2 = e.getValue();
            if (v1 == v2 || (v1 != null && v1.equals(v2)))
                return true;
        }
        return false;
    }

    public final int hashCode() {
        return (key==null   ? 0 : key.hashCode()) ^
               (value==null ? 0 : value.hashCode());
    }

    public final String toString() {
        return getKey() + "=" + getValue();
    }
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
user2155454
  • 95
  • 3
  • 12

2 Answers2

1

Map.Entry is a representation of a key-value pair, in a map. All of this methods can be used for comparing key-value pairs, not for comparing key-objects.

Egor
  • 1,334
  • 8
  • 22
1

Entryes are objects too, it's entirely possible to compare them for equality or to use them as keys in a map.

In addition, they are sometimes used as a poor man's Pair class: Didn't Java once have a Pair class?, https://www.baeldung.com/java-pairs, https://www.techiedelight.com/five-alternatives-pair-class-java/ and for this use you really want these implementations of equals and hashCode.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487