1

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?

wildplasser
  • 43,142
  • 8
  • 66
  • 109
eosd441
  • 97
  • 1
  • 2
  • 6

1 Answers1

6

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.

Community
  • 1
  • 1
Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93