What is the purpose of overriding hashcode in a java object?

I know that multiple objects have the same hash code in java objects. This does not create any problems at all. So, What is the purpose of overriding hashcode in java ...

In what situation is it advisable to override the hash code in java?

+4
source share
1 answer

In what situation is it advisable to override the hash code in java?

When you redefine equals , basically. This means that hash-based collections (e.g. HashMap , HashSet ) can very quickly find a set of candidate objects that will be equal to the one you are looking for (or trying to add, or something else). If you have a large collection, you split it into buckets using a hash code. When you try to look at something, you will find the hash code of the object you passed in and look for objects with the same hash code in the corresponding bucket. Then for each object with exactly the same hash code, you call equals to see if both objects are really the same.

See the hash table Wikipedia article for more information.

EDIT: Quick note on choosing hash codes ...

It is always valid to simply override hashCode and return some constant (the same for each call) regardless of the contents of the object. However, at this point you lose all the advantages of a hash code - basically a hash container will think that any instance of your type can be equal to any other, so looking for one of them will consist of calls to O (N) on equals .

At the other end of the scale, if you do not correctly implement hashCode and return a different value for calls to equal objects (or two calls of the same object twice), you cannot find the object when it is searched - different hash codes will exclude equality, therefore equals will never be called.

Then there is the aspect of variability - it is usually a bad idea for equals and hashCode use mutable aspects of an object: if you mutate an object in a hash variable after you inserted it into the hash collection, you won’t be able to find it again because the hash during the insertion will no longer be correct.

+8
source

Source: https://habr.com/ru/post/1494782/


All Articles