开发者

Overriding equals() and hashCode() in Java [duplicate]

This question already has answers here: Closed 12 years ago.

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

Overriding equals() and hashCode() in Java [duplicate]


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜