Setting own class as key in java Hashmap?

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

You need to implement hashCode() and equals(). CompareTo() is additionally required for sorted map/set. See this question for details.

You should implement equals() and hashCode(). Your class should also be immutable. If it is mutable, it's hash code can change after adding it to map.

Then the map can have problems finding it.

1 +1 for the inmutable – helios Sep 8 '10 at 7:57 He is doing new before put and add. So immutable does not matter. Still a good point, +1.

– fastcodejava Sep 8 '10 at 8:19.

1) In general for collections, what you want to override is the equals() method (and also the hashcode() method) for your class. CompareTo()/Comparable and Comparator are typically used for sorting and only take the place of using the equals() method for object equivalance in some cases - examples are implementers of SortedSet such as TreeSet. 2) Please conform to Java naming standards in your code.

Your class names should be capitalized... e. G new MyKey(dummyArguments). See http://www.oracle.com/technetwork/java/codeconventions-135099.html#367 (and http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) for more detail.

Class renamed. Thanks for pointing out. :) – Nikhil Garg Sep 8 '10 at 7:30.

HashMap doesn't check compareTo(); HashMap checks hashCode() and equals().

When using Collections that rely on hashing like Map and Set you have to implement the equals() and hashCode() to guarantee correct functionality. If you don't a new myKey will always be different from the key stored in the map because it uses the default implementations of equals() and hashCode().

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions