开发者

Java equals and hashCode methods - technical constraints

I've got question about java's equals(Object o) and hashCode() methods. Wh开发者_开发知识库at are the technical constraints of implementation this both methods? Is there something that I can't do during implement this methods?


None. It's just two methods in Object class. You could even change an object's state within this methods and this will freak out every developer and system but it's still valid from technical point of view.


You can technically anything inside them you can do in any other methods.

Instead what you concern yourself with are the practical and contractual obligations of the methods.

Good rules of thumb:

  1. If you override one, override the other.
  2. Variables used in one should be used in the other.


a given object must consistently report the same hash value two objects which equals() says are equal must report the same hash value - so no timestamps in the hashcode :).

Two unequal objects can also have the same hashcode, though it is better to make the hashcode difficult to repoduce.


All you need to remember, is:

  1. those constrains are very important
  2. all are very well documented in javadoc for Object.hashCode() and Object.equals()

Make sure you understand it every time you override any of those methods.


Is there something that I can't do during implement this methods?

Well, as a rule of thumb (and as already @RHT mentioned above and @Antti Sykäri explains here) do your future self a favor and always use EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. Because, quite frankly, at least in my case I never get to remember all the nitty-gritty details that a correct implementation would require. ;-)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜