15
votes

When we have equals(), compareTo() methods why there is a hashcode() method in Java?

And in case if we use HashTable we have to override hashcode() method, Is there any special reason except fast accessing of random keys? If we override the hashcode() method what would be the probable implementation ?

How Java ensures object uniqueness in memory?


Hashcodes are typically used to enhance the performance of large collections of data.

In hashing we calculate hash code. it's an additional task. When we do additional operation for each object that is added to a collection. How the performance gets improved?

2
why is there a hashing technique? To implement those methods by default. you can override them if you want. - SoWhat
PLease edit your question so that people can understand what you actually want to know. - Ajay Bhojak
@AjayBhojak Edited the question - MaheshVarma
This question should be reopened, as now with edits it should be clear what is being asked. - eis

2 Answers

13
votes

You must always override equals and hashCode in tandem, to satisfy their interdependent contracts. A class which implements them contradictorily is simply broken and unacceptable under even the minimum software engineering standards.

As to why one would ever use the hashtable data structure: because it is the fastest option around for random-access key-value storage.

0
votes

Using the compareTo method you establish a "total order" for your objects. A total order is a fairly weak property: it can only tell you if one object is "less than" another, but it gives you no idea of "how far apart" two objects are.

For example, if you have a N objects in a key-value data structure and you want to find the value for a given key. Having only a total order you need at least O(log N) comparisons to find a matching key.

A hash code is a stronger property because it can tell you if two objects are somewhat similar or completely different. Thanks to this a hash table can find a value for a key with O(1) operations.