MattRS
MattRS

Reputation: 428

hashcode collisions for different classes

I have two simple wrapper classes around an Integer field, where I had to override equals() and hashCode(). In the end, they both use the same algorithm for hashCode(), so if the Integer field is the same, the hash codes collide.

Since the Objects are different types does this matter, or should I only care if I expect to mix them as keys in the same HashMap?

Upvotes: 0

Views: 154

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

If you are likely to have a hash map with objects of both types with the same values, then that is obviously going to be a potential performance problem. HashMap and the like don't look at the actual runtime class - and indeed there isn't a standard way to tell whether two objects of different classes can be equal (for instance, Lists with the same values in the same order generated by ArrayList and Arrays.asList should compare equal). For HashMap, I'm guessing the hit wont be too bad, but could be worse for, say, a probing implementation where there is a significant gain for getting a hit on first inspection.

Upvotes: 1

dlev
dlev

Reputation: 48596

hashCode() being equal for two objects says "there's a chance these objects are equal, take a closer look by calling equals()". As long as the equals() methods for those classes are correct, the hash codes being the same is not a problem.

The general rule for hashCode() is that if two objects are equal, their hash codes should also be equal. Note that the rule is not "if two objects have the same hash code, then they should be equal."

Upvotes: 13

Related Questions