Kevin
Kevin

Reputation: 23634

Do we need to override hashcode method?

I was looking at the java.lang.Object and also reading couple of questions in StackOverflow on the same topic.

equals() method is used to determine the equality of two objects.

Basically, if you want to store an object in a collection (Map, Set, List) then you have to implement equals and hashCode methods according to the contract defined in the documentation.

Correct me if i am wrong, If i am not storing my Class inside an collection, then i don't need to over-ride the hashcode method as the equals method would be more than enough.

Upvotes: 2

Views: 1355

Answers (5)

Juned Ahsan
Juned Ahsan

Reputation: 68715

It is recommended to override hashCode if you are overriding equals but it is not mandatory. This method is supported for the benefit of hash tables such as those provided by HashMap.

Note: So if you are sure that you or anyone else will never use your class object to be stored in a hashed collection then skip it. Otherwise override it.

Upvotes: 2

Marc
Marc

Reputation: 1976

If you don't put your object into HashMap or similar Collection / Map types then you don't to override the hashCode function in your class.

Upvotes: 1

rocketboy
rocketboy

Reputation: 9741

Overriding hashCode() will help in a healthy categorization for all Hash based implementations in Java. The buckets will distributed depending on the hashCode() method's value.

Upvotes: 0

Henry
Henry

Reputation: 43738

This is correct. However, if you later (when the shortcut is long forgotten) put it into a Map or Set, things will crash badly.

Upvotes: 6

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

From Object#equals javadoc:

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

This means, if you will override equals, then it will be good to also override hashCode to follow this contract, but it is not required.

Upvotes: 0

Related Questions