I have a doubt with equals and hascode methods. I test this code.
If two objects are equal, their hashCodes must return the same integer. In this example the hascode isn't the same, because it isn't implemented and it returns the hashCode of class Object, that always returns diferents hashcode for diferent objects.
I don't understand why this code works and why the hashMap is able to find the objects if the last is true. If the contract is only valid for hash, why does this code works?
And if I don't want to use the TestEqualsHashcode class objects to use in keys of hash, why I must override hashCode if I override equals? The code compile and works
[ December 13, 2007: Message edited by: nico dotti ]
Joined: Oct 09, 2007
Here's another run at it:
Joined: Dec 06, 2007
Hi Nico, I'm grateful for your efforts and I understand you have said. But I have no clear the concept yet. There are a lot of question like that: "if you override equals, you MUST override hashcode", and the only one reason for this is to have a good hash. The MUST word, may be changed by this: "If you override equals, and if you want to use the objects as a key in a hash collection, then override properly hashcode". The only diference that I have found without override hashcode is that internally, I have a non optimized hash. Am I wrong?