What is the purpose of hashcode method in java? [duplicate]

霸气de小男生 提交于 2019-12-21 03:33:06

问题


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?


回答1:


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.




回答2:


Check the following Link to understand why hashing is used

1: http://java.dzone.com/articles/java-hashing and the following Link also wil help you.




回答3:


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.




回答4:


why there is a hashcode() method in Java?

Basically whenever we insert in a unique data structure, the data structure make sure that there is no duplicate object is inserted. How do it do that??
This is done by the contract the objects are implementing, hashcode() that the unique id as SSN of a person. But if you want to retrieve a particular object then guess what should be called after matching SSN, yes you guessed right it is equals().



来源:https://stackoverflow.com/questions/18078779/what-is-the-purpose-of-hashcode-method-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!