S. Palanigounder wrote:If hashCode is overwritten correctly, nothing will happen. The object can be the correct key used in HashMap.
Michael Angstadt wrote:No, it needs both to work properly.
I think this depends on what "overwritten correctly" and "work properly" means. If "overwritten correctly" just means that the hashCode / equals contract is not violated, then the object can be used as a key in a hashmap. And if "work properly" means that equality is based on instance, and not based on the value, then it should work properly. Of course, that could also have been achieved by not overriding hashCode() in the first place.
Please look in books like Thinking in Java by Bruce Eckels, Effective Java by Joshua Bloch.
Please search for Angelika Langer's pages about the Java equals method.
Please search these fora because this question comes up frequently.
S. Palanigounder wrote:Ulises, Can you provide the override implementation for hashCode and equals that works?
Well there is no equals and hascode implementation that can fit for all the objects.
Depending on the class you have created is the implementation you can do. What I can give you are the rules for the implementation.
If x == y then it must be that x.hashcode == y.hashcode
If x != y then x.hashcode might be == or != than y.hashcode
If x.equals(y) is true then it must be that x.hashcode == y.hashcode.
If !x.equals(y) then x.hashcode might be == or != than y.hashcode.
if x.equals(y) and y.equals(z) then x.equals(z). The same goes for hashcode.
Once you have implemented both methods and they behave as the rules stated before then you can say that you have a correct implementation of both methods.