Mohamed Sanaulla wrote:Syntactically it is correct. But Semantically its wrong Try to put them in a Hashmap and try to retrieve the elements put in the map. This is where the contract comes into picture. It is because- it uses the hashCode to search for the relevant bucket and then uses equals() to find the exact element
Just as Mohamed Sanaulla mentions, your code will compile but it will not work properly since it doesnt follow the hashcode contract.
Its a big difference in code that compiles and code that works as intended.
Consider the following.
Even though obj1 and obj2 clearly are equal since obj1.equals(obj2) evaluates to true you cant find obj1 in the map using obj2 since the hashcodes are not equal.
As long as you clearly understand how equals and hashCode relate to eachother and are used in collections
you should be fine.
Its described clearly in K&B book and im sure you can find lots of information about it if you
search