3

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;
    }
}
Andrew Regan
  • 4,887
  • 6
  • 35
  • 67
abhijit
  • 31
  • 2
  • 1
    An `equals` method that always returns `false` is invalid, because it does not conform to the contract of `equals`. [There are constrains on the implementations of the `hashCode` and `equals` methods](http://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java) – Raedwald Feb 05 '16 at 13:55
  • `== and equals() are not the same` – Shark Feb 05 '16 at 13:59

2 Answers2

7

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.

Alex Salauyou
  • 13,188
  • 4
  • 39
  • 67
0

Returning always false in equals is not a good idea. By definition equals should be reflexive:

It is reflexive: for any non-null reference value x, x.equals(x) should return true.

For the hash table will return null because it uses equals when hash code is equal while for hash map will check == for objects first

user1121883
  • 5,153
  • 3
  • 30
  • 34