Following is a qoute from K & B
SCJP 1.4 book:
".... equals() and hashCode() are bound together by a joint contract that specifies if two objects are considered equal using the equals() method, then they must have identical hashcode values..."
Following is a snippet of code from the same book which I have modified to print the hashcode values of the objects and see if the values are equal:
If you run this program, you'll find the hashcode values for the objects are different. I know I haven't overridden the hashCode() method and hence the different hashcode values in the output.
Is it only necessary to override the hashCode() method only when it is going to be used by some collection classes? And finally, can this be considered as a "correct or appropriate" implementation as it clearly violating the abovementioned contract? Thanks!