Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behaviors for HashMap and Hashtable when Equals overridden to always return False [duplicate]

Tags:

java

I am little confused as I thought HashMap and Hashtable should behaves same way when it comes to hashCode and equals method. in this example below my key class has overridden equals method to always return false.

does any one have any idea that can explain in this difference in behavior because it seem like output is different for both

value null

value null

value Value 1

value Value 2

import java.util.Hashtable;
import java.util.HashMap;

public class HashTest {

    public static void main(String[] args) {

        Hashtable ht = new Hashtable();
        HashMap hm = new HashMap();
        KeyClass k1 = new KeyClass("k1");
        KeyClass k2 = new KeyClass("k2");

        ht.put(k1, "Value 1");
        ht.put(k2, "Value 2");
        hm.put(k1, "Value 1");
        hm.put(k2, "Value 2");

        System.out.println("value " + ht.get(k1));
        System.out.println("value " + ht.get(k2));

        System.out.println("value " + hm.get(k1));
        System.out.println("value " + hm.get(k2));
    }
}

class KeyClass {
    String key;

    public KeyClass(String str) {
        key = str;
    }

    @Override
    public int hashCode() {
        return 2;
    }

    @Override
    public boolean equals(Object obj) {
        return false;
    }
}
like image 975
abhijit Avatar asked Jan 29 '26 02:01

abhijit


1 Answers

This happens because HashMap first uses == in equality check:

public V get(Object key) {
   //...
   if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
      return e.value;

So, despite equals() returns false, same object is treated as the same key.

like image 169
Alex Salauyou Avatar answered Jan 30 '26 16:01

Alex Salauyou