i found that if i insert two different objects with same hashcode in the map they latter overrides the previous value
But you aren't using two different objects for keys. You're only using one object all the time, namely the Integer whose value is 1. Try actually using the Animals and Vegetables objects as keys, which I believe is what you meant to try.
posted 5 years ago
Thanks for your reply i corrected the code as
and got the output as :
For Key com.example.Maps.Vegetables@1 Value is Carrot
For Key com.example.Maps.Vegetables@1 Value is Cabbage
so both keys with same hashcode are stored in my hashmap in the same bucket.
That equals method is incorrect. It must never throw an Exception, but you will suffer a ClassCastException if you pass an object of any other type.
if (boo) return true; else return false. It is simply
return boo; Try
return obj instanceof Vegetable && ((Vegetable)obj).name.equals(this.name); That will still cause problems if you manage to set the name to null. Find out about the Objects class.
Your hashCode method might fulfil the “letter of the law” of its general contract but it is a very bad idea to return the same value from all instances. Again find out about the Objects class.
Campbell Ritchie wrote:That equals method is incorrect. It must never throw an Exception, but you will suffer a ClassCastException if you pass an object of any other type.
For example if you uncommented line 53 in the last posted code; that would result in the map trying to compare the new Animals object with the Vegetables objects which are already in the Map. Perhaps that was why the OP left that line commented.
We find this kind of rampant individuality very disturbing. But not this tiny ad: