How do we decide on the best implementation of hashCode()
method for a collection (assuming that equals method has been overridden correctly) ?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
First make sure that equals is implemented correctly. From an IBM DeveloperWorks article:
Then make sure that their relation with hashCode respects the contact (from the same article):
Finally a good hash function should strive to approach the ideal hash function.
There's a good implementation of the Effective Java's
hashcode()
andequals()
logic in Apache Commons Lang. Checkout HashCodeBuilder and EqualsBuilder.about8.blogspot.com, you said
I cannot agree with you. If two objects have the same hashcode it doesn't have to mean that they are equal.
If A equals B then A.hashcode must be equal to B.hascode
but
if A.hashcode equals B.hascode it does not mean that A must equals B
If you're happy with the Effective Java implementation recommended by dmeister, you can use a library call instead of rolling your own:
This requires either Guava (
com.google.common.base.Objects.hashCode
) or the standard library in Java 7 (java.util.Objects.hash
) but works the same way.@about8 : there is a pretty serious bug there.
same hashcode
you probably want something like
(can you get hashCode directly from int in Java these days? I think it does some autocasting.. if that's the case, skip the toString, it's ugly.)
If you use eclipse, you can generate
equals()
andhashCode()
using:Using this function you can decide which fields you want to use for equality and hash code calculation, and Eclipse generates the corresponding methods.