简体   繁体   中英

Strange results after overriding hashcode() method

I have the following situation-

  1. I am creating a HashMap using generics. The key is of type TestHashMap, and the value is of type String.

  2. In the main method of TestHashMap, I use three instances of TestHashMap as keys to store three different strings.

  3. I override the hashcode() method so that it returns a different integer on each call.

  4. Then I extract the keys in the HashMap and print out the corresponding values.

This gives me totally unexpected results- I get a null for each value of the three key-value pairs.

Note that if, instead of returning different integers on different calls of hashcode(), I just returned the same integer, everything works fine.

This has me really stymied. Any help will be much appreciated.

Here is the code. You should be able to run it if you copy it as is.

import java.util.HashMap;
import java.util.Set;

public class TestHashMap {
    private static int hash = 0;    
    public static void main(String[] args) {
        HashMap<TestHashMap,String> h = new HashMap<TestHashMap,String>();
        TestHashMap thm1 = new TestHashMap();
        TestHashMap thm2 = new TestHashMap();
        TestHashMap thm3 = new TestHashMap();

        h.put(thm1, "one");
        h.put(thm2, "two");
        h.put(thm3, "three");

        Set<TestHashMap> keys = h.keySet();
        for(TestHashMap k : keys){
            System.out.println(k + " " + h.get(k));
        }
    }

    @Override
    public int hashCode(){ return hash++;}
}
  • When you put an object into a map, the map will read the key's hashcode and place it into the appropriate bucket;

  • when you later get an object by the same key, the map will again read the key's hashcode and look for an object equal to the key in that bucket;

  • but your key gives the map a different hashcode each time. So the poor map is tricked into looking in the wrong bucket.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM