简体   繁体   中英

Is Java hashCode() method a reliable measure of object equality?

I am currently working on comparing two complex objects of the same type, with multiple fields consisting of data structures of custom object types. Assuming that none of the custom objects has overriden the hashCode() method, if I compare the hashcodes of every field in the objects, and they will turn out to be the same, do I have a 100% confidence that the content of the compared objects is the same? If not, which method would you recommend to compare two objects, assuming I can't use any external libraries.

Absolutely not. You should only use hashCode() as a first pass - if the hash codes are different, you can assume the objects are unequal. If the hash codes are the same, you should then call equals() to check for full equality.

Think about it this way: there are only 2 32 possible hash codes. How many possible different objects are there of type String , as an example? Far more than that. Therefore at least two non-equal strings must share the same hash code.

Eric Lippert writes well about hash codes - admittedly from a .NET viewpoint, but the principles are the same.

No, lack of hashCode() collision only means that the objects could be identical, it's never a guarantee.

The only guarantee is that if the hashCode() values are different (and the hashCode() / equals() implementations are correct), then the objects will not be equal .

Additionally if your custom types don't have a hashCode() implementation, then that value is entirely useless for comparing the content of the object, because it will be the identityHashCode() .

If you haven't overriden the hashCode() method, all of your objects are unequal. By overriding it you provide the logic of the comparison. Remember, if you override hashCode(), you definitely should override equals() . EDIT: there still can be a collisionm of course, but if you didn't override equal() , your objects will be compared by reference (an object is equal to itself).

The usual JVM implementation of Object.hashCode() is to return the memory address of the object in some format, so this would technically be used for what you want (as no two objects can share the same address).

However, the actual specification of Object.hashCode() makes no guarentees and should not be used for this purpose in any sensible or well-written piece of code.

I would suggest using the hashCode and equals builders available in the Apache commons library, or if you really can't use free external libs, just have a look at them for inspiration. The best method to use depends entirely on what "equal" actually means in the context of your application domain though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM