java - Different behaviors for HashMap and Hashtable when Equals overridden to always return False -


i little confused thought hashmap , hashtable should behaves same way when comes hashcode , equals method. in example below key class has overridden equals method return false.

does 1 have idea can explain in difference in behavior because seem output different 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 treated same key.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -