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 inHashMapTest? I guess not, and that’s the default behavior ofhashCode()inherited fromjava.lang.Object(you are actually using two different objects.) Have a look at this question to provide correcthashCode/equalsimplementations for your classes.