Nikhil Garg Nikhil Garg - 1 year ago 78
Java Question

Setting own class as key in java Hashmap

I have a class which I want to set up as keys in HashMap. I already have implemented the compareTo method for that class. But still when I do:

map.put(new MyKey(dummyArguements) , dummyValue );
System.out.println(map.get( new MyKey(dummyArguements) ) );

I get null.
So that means hashmap is not able to identify that the two keys (for get & put call) are same.

Could someone help me here please ?

Answer Source

You need to implement hashCode() and equals(). compareTo() is additionally required for sorted map/set.

See this question for details.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download