Java Hashing – Why Use `equals` if `hashcode` is Already Implemented?

hashingjava

I got a question about why we need equals if we have hashcode.

My first attempt was the answer because collision. But we corrected starting point with the assumption that we have not many objects so there is no collision at all.

My second attempt was the answer because of the speed. But I also got the reply that there is something conceptual difference between hashcode and equals.

So I read a lot of posts, the java doc and can not find the answer. Do I miss something?

Best Answer

To put it bluntly: they serve different purposes.

  • Equals is for testing equality.
  • Hashcode is in order to produce an int (hopefully well distributed)

if your hashcode is unique, you could as well use it for equality. However, for many kind of objects, producing such a unique hash is plainly impossible.

Imagine an object containing two ints a and b. There is no way to produce a unique int hash for such an object. So you still need equality to compare them.

As for the comparator, it's usually a bad idea to use the output as hash because the result is not well distributed, resulting in lots of collisions when used in hash maps or similar data structures.

Related Topic