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.
I am currently working on comparing two complex objects of the same type, with
Share
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 callequals()to check for full equality.Think about it this way: there are only 232 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.