Overriding the default implementations of the Java class equals method provides a higher degree of semantic comparability between object instances. Under the default implementation, two references are equal only if they refer to the exact same object.
Cases where hashCode must be overridden include the following:
Cases where hashCode must be overridden include the following:
- if a class overrides the equals method it must override hashCode
- when they are both overridden, equals and hashCode must use the same set of fields
- if two objects are equal, then their hashCode values must be equal as well
A simple way of overriding the equals and hashcode methods in Eclipse is to generate them using the menu/context menu Source -> Generate hashCode() and equals().
All hash-based collections assume that an object's hash value will not change whilst it is in use as a key in the collection. If assumption were violated unpredictable results would occur.
0 comments:
Post a Comment