To clarify the role of hashcode, you must first know the collection in Java. (Unclear see the Java foundation of the set of framework specific explanation (ii) List and Java basis of the set of framework specific explanation (c) set)
There are two classes of collection collections in Java. One is the list, and the other is set, the elements in the set are ordered, the elements can be repeated, the elements are unordered and the elements are not repeated.
We usually use the Object.Equals method to infer whether two elements are repeated. That is, when we want to find out whether an object is included in an element. is to take out each element and compare it to the element you are looking for. When you find that an element is equal to the result of the Equals method for the object you are looking for. Stops the search and returns positive information, otherwise the negative information is returned. Suppose a collection has very many elements, such as thousands of elements. And not including the object to look for, it is thought that our program needs to remove thousands of elements from the collection to get the results one by one, so someone invented a hashing algorithm to improve the efficiency of finding elements from the collection. This way, a collection is divided into several storage areas. Each object can compute a hash code that can group the hash code, each group corresponding to a storage area, based on the hash code of an object can determine the object should be stored in that area.
Hashcode can understand this: it returns a value that is converted from the memory address of the object. this way, when a collection is added to a new element, the Hashcode method of the element is called before it can be positioned at the physical location where it should be placed.
Assuming there are no elements in this position, it can be stored directly in this position, no matter what the comparison. Assuming there is already an element in this position, the Equals method that calls it is compared to the new element, and the same is not saved, and the other addresses are not hashed .
In this way, the number of actual calls to the Equals method is greatly reduced. Almost only one or two times.
Because of the high efficiency of using the hashing algorithm. The important implementation class HashSet of the set interface is actually the hashing algorithm used to infer the repeated elements. Please refer to the framework of Java Foundation for specific explanation (c) Set chapter
Summary:
The Hashcode method of Java Foundation is explained in detail