简体   繁体   中英

HashMap different hashcodes return different values? Java

I have a hashmap of two objects, but it seems to return different values because the hashcode is different. Ex.

HashMap<HashMapTest, String> newMap = new HashMap<HashMapTest, String>();
    newMap.put(new HashMapTest("test"), "line");
    System.out.println(newMap.get(new HashMapTest("test")));

the hashcodes are different when I put it in the hashmap and when I get it from the hashmap. Is there any way of fixing this?

Did you provide your custom implementation of the hashCode() method in HashMapTest ? I guess not, and that's the default behavior of hashCode() inherited from java.lang.Object (you are actually using two different objects.) Have a look at this question to provide correct hashCode/equals implementations for your classes.

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