-1

I know that when we override equals() method then we need to override hashcode() as well and other way around.

But i don't understand why we MUST do that?

In Joshua Bloch Book it is clearly written that we must do that, because when we deal with hash based collections, it is crucial to satisfy the Hashcode contract and I admit that, but what if I am not dealing with hash-based collections?

Why is it still required ?

Neeraj Jain
  • 7,077
  • 3
  • 26
  • 53
  • Because any two objects which are `equal` MUST, by definition, have the same `hashcode`, how could they be `equal` otherwise? – MadProgrammer Mar 20 '15 at 04:52
  • Because someday you *will* try to stuff it into a hash-based collection, even if only indirectly. It's a latent bug that's easily avoided. – chrylis -cautiouslyoptimistic- Mar 20 '15 at 04:53
  • Because someone else might. Or you, in the future. It is equivalent to having `int subtract(a, b) { return a + b; }` in your code. You might remember it now, but if your code gets bigger, or gets a new developer... Ouch. If you don't get burned by it, it is only by luck. – Amadan Mar 20 '15 at 04:53

5 Answers5

2

Why to Override Equals ?

A programmer who compares references to value objects using the equals method expects to find out whether they are logically equivalent, not whether they refer to the same object .

Now coming to HashCode

Hash function which is called to produce the hashCode should return the same hash code each and every time, when function is applied on same or equal objects. In other words, two equal objects must produce same hash code consistently.

Implementation of HashCode provided by Object Class is not based upon logical equivalency ,

So Now if you will not override hashCode but override equals, then according to you 2 Objects are equals as they will pass the equals() test but according to Java they are not .

Consequences :

  1. Set start allowing duplicates !!!
  2. Map#get(key) will not return the correct value !!
  3. and so on many other consquences..................
Neeraj Jain
  • 7,077
  • 3
  • 26
  • 53
1

Data structures, such as HashMap, depend on the contract.

A HashMap achieves magical performance properties by using the hashcode to bucketize entries. Every item that is put in the map that has the same hashcode() value gets placed in the same bucket. These "collisions" are resolved by comparing within the same bucket using equals(). In other words, the hashcode is used to determine the subset of the items in the map that might be equal and in this way quickly eliminate the vast majority of the items from further consideration.

This only works if objects that are equal are placed in the same bucket, which can only be ensured if they have the same hashcode.

NOTE: In practice, the number of collisions is much higher than may be implied above, because the number of buckets used is necessarily much smaller than the number of possible hashcode values.

Rob
  • 5,634
  • 1
  • 21
  • 28
0

Because that is the way it is meant to be:

Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().

What issues should be considered when overriding equals and hashCode in Java?

There are use-cases where you don't need hashcode(), mostly self-written scenarious, but you can never be sure, because implementations can and might be also relying on hashcode() if they are using equals()

Community
  • 1
  • 1
Felk
  • 6,165
  • 1
  • 27
  • 51
0

As per Joshua Bloch book;

A common source of bugs is the failure to override the hashCode method. You must override hashCode in every class that overrides equals. Failure to do so will result in a violation of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

Failing to override hashcode while overriding equals is violation the contract of Object.hashCode. But this won't have impact if you are using your objects only on non hash based collection.

However, how do you prevent; the other developers doing so. Also if an object is eligible for element of collection, better provide support for all the collections, don't have half baked objects in your project. This will fail anytime in the future, and you will be caught for not following the contacts while implementing :)

Kanagavelu Sugumar
  • 16,614
  • 19
  • 77
  • 92
0

This question is answered many times in SO, but still I will attempt to answer this .

In order to understand this concept completely, we need to understand the purpose of hashcode and equals, how they are implemented, and what exactly is this contract(that hashcode also should be overridden when equals is overridden)

equals method is used to determine the equality of the object. For primitive types, its very easy to determine the equality. We can very easily say that int 1 is always equal to 1. But this equal method talks about the equality of objects. The object equality depends on the instance variables or any other parameter (depend purely on the implementation - how you want to compare).

This equal method needs to be overridden if we want some customized comparison, lets say we want to say that two books are same if they have same title and same author, or I can say two books are equal if they have same ISBN.

hashcode method returns a hash code value of an object. The default implementation of the Object hashcode returns a distinct integers for distinct objects. This integer is calculated based on the memory address of the object.

So we can say that the default implementation of the equals method just comapres the hashcodes to check the equality of the object. But for the book example - we need it differently.

Also Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.

In case of not using a hash based collection, you can break the contract and need not to override the hashcode method - because you ll not be using the default implementations anywhere but still I would not suggest that and would say to have it as you may need it in future when you put those things in collection

shikjohari
  • 2,147
  • 8
  • 23