Possible Duplicate开发者_StackOverflow社区:
Overriding equals and hashCode in Java
All,
I have defined my class and which to override equals() and hashCode () methods as well. But I have no idea of what specifically these methods should be implemented for my own class. Can anyone please shed some light on the implementation of these methods for custom classes?
You say you already know which one of your custom classes need to override hashCode/equals? Then you also know what attributes (global variables) determine equality of each class.
When you know these attributes you can implement hashCode/equals either manually or by generating the methods using a modern IDE such as Eclipse, NetBeans, etc. In Eclipse there's an option named "Generate hashCode() and equals()" under the "Source" menu
For equals, the answer depends on what your business need is, i.e. what does it mean for your objects to be equals.
hashCode() should always return a unique value for an object, unless that object is equal to another object. It should depend on the values of the properties on your object.
Java theory and practice: Hashing it out
Basically, if you want to store an object in a collection (Map, Set, List) then you have to implement equals and hashCode methods according to the contract defined in the documentation.
Otherwise, many collection implementations won't have the expected behaviour. For implementation clues, read the Object Javadoc for equals and hashcode.
Read the API documentation of the two methods in java.lang.Object
. It describes very exactly how overriding implementations should behave.
When implementing equals() make sure you understand the difference between equality and identity. Two object instances may be 'equal' but may not be identical. a.equals(b) is a test for equality, which your business rules should define. == is a test for object identity (same object instance)
精彩评论