The above code for some reason isnt able to get the value back from the HashMap. I printed out the whole HashMap and I can see that it contains the said key and value. I have also implmented the equals method in the MyKey class but for some reason it is never called (I checked that by putting a println statement in the equals method) Can anyone find the bug? Thanks PMc
You said you overrode the equals method; did you remember to override the hashCode() method as well? I think HashMap checks hashCode() first, which it uses to put values in "buckets", then checks keys in the bucket for equality. If you didn't override hashCode() and assuming MyKey is a direct subclass of Object, then the key you used with put() will have a different hashCode() value from the key you use with get() and you won't get to the point where equals() gets called.
You probably need to implement the hashCode() method in MyKey. In general you should always override hashCode() whenever you override equals(), and vice versa. Effective Java by Joshua Bloch has a good short section on making hashcode() and equals() methods.
Originally posted by Paul McKenna: HashMap m = new HashMap(); MyKey key = new MyKey(MyConstants.PRIMARY_KEY); // MyKey is just a wrapper class around a string constant m.put(key, "Nothing here"); .. .. System.out.println("Value for mykey : "+key);// use the already defined key .. ..
Perhaps this might work, if Object.hashcode() is not overridden. -GB.
Joined: Jan 17, 2003
Yep! Thank you! I had to override the hashCode method. It worked once that was done PMc