Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the purpose of overriding hashcode in java object? [duplicate]

I know multiple object having same hashcode in java objects.It doesn't make any problem at all.So, What is the purpose of overriding hashcode in java...

In which situation it is advisable to do override the hashcode in java?

like image 649
Saravanan Avatar asked Feb 16 '23 16:02

Saravanan


1 Answers

In which situation it is advisable to do override the hashcode in java?

When you override equals, basically. It means that collections which are hash-based (e.g. HashMap, HashSet) can very quickly find a set of candidate objects which will be equal to the one you're looking for (or trying to add, or whatever). If you have a large collection, you split it into buckets by hash code. When you're trying to look something up, you find the hash code of the object you've been passed, and look for objects with the same hash code within the relevant bucket. Then for each object with the exact same hash code, you call equals to see whether the two objects are really the same.

See the Wikipedia article on hash tables for more information.

EDIT: A quick note on the choice of hash codes...

It's always valid to just override hashCode and return some constant (the same for every call) regardless of the contents of the object. However, at that point you lose all benefit of the hash code - basically a hash-based container will think that any instance of your type might be equal to any other one, so searching for one will consist of O(N) calls to equals.

On the other end of the scale, if you don't implement hashCode correctly and return a different value for calls to equal objects (or two calls on the same object twice) you won't be able to find the object when you search for it - the different hash codes will rule out equality so equals will never even be called.

Then there's the aspect of mutability - it's generally a bad idea for equals and hashCode to use mutable aspects of an object: if you mutate an object in a hash-changing way after you've inserted it into a hash-based collection, you won't be able to find it again because the hash at the time of insertion will no longer be correct.

like image 92
Jon Skeet Avatar answered May 01 '23 07:05

Jon Skeet