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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With