Java Collection-hashCode, java-hashcode

Source: Internet
Author: User

Java Collection-hashCode, java-hashcode
Role of hashCode

There are two types in the Java Set: List and Set. The difference between them is that the element division in the List Set is ordered and can be repeated, elements in the Set are unordered and cannot be duplicated. The List is well processed, but how can we ensure that the elements are not repeated for the Set? Whether equals () is equal Through iteration. A small amount of data is acceptable. When we have a large amount of data, the efficiency can be imagined (of course, we can use algorithms for optimization ). For example, if we insert 1000 million data into HashSet, do we really need to iterate 1000 times and call the equals () method 1000 times? HashCode provides a solution. How to implement it? Let's first look at the source code of hashCode:

public native int hashCode();

When we add an element to a set, the set will first call the hashCode method, so that we can directly locate the location it stores. If there are no other elements, it will be saved directly. If an element already exists, call the equals method to match whether the two elements are the same. If they are the same, they are not saved. If they are different, they are hashed to other locations.

In this way, when we store a large number of elements, we can greatly reduce the number of calls to the equals () method, greatly improving the efficiency.

Therefore, the role of hashCode in the previous step is to find the domain (to find the location of an object in the area of the collection ). HashCode can divide a set into several regions. Each object can calculate its hash code. It can group the hash code. Each group corresponds to a storage region, the region where the object is stored can be determined based on the hash code of an object, which greatly reduces the number of query matching elements and improves the query efficiency.

The importance of hashCode for an object

Is hashCode important? It is not important. It is cumbersome for List sets and arrays, but it becomes very important for HashMap, HashSet, and HashTable. Therefore, you must pay attention to hashCode when using HashMap, HashSet, and HashTable. For an object, its hashCode process is a simple Hash algorithm. Its implementation process plays a very important role in implementing the object access process.

We have mentioned two data structures, HashMap and HashTable. Although they have several differences, their implementation principles are the same, here I take HashTable as an example to illustrate the importance of hashCode for an object.

An object is bound to have several attributes. How to Select attributes for hashed testing a person's design ability. If we hash all the attributes, this will be a bad design, because the hashCode method of the object is not called all the time. If too many attributes are involved in the hash, the required operand time will be greatly increased, which will seriously affect the program performance. However, if a small number of objects are involved in the hash, the diversity of the hash will be weakened, resulting in a large number of hash "conflicts", in addition to being unable to make good use of space, to some extent, the query efficiency of objects is also affected. In fact, the two are a contradiction, and the diversity of hash will reduce the performance.

Then how to design the hashCode of the object. A solution was found on the Internet: Set a cache identifier to cache the current hash code. The calculation is performed only when the object involved in the hash changes, otherwise, the cached hashCode can be called to greatly improve the performance.

Run the following code to calculate the index position of an object in the table [] array in HashTable:

    int index = (hash & 0x7FFFFFFF) % tab.length;

Why & 0x7FFFFFFF? Because the hashCode of some objects may be negative, performing operations with 0x7FFFFFFF can ensure that the index is a positive number. In this step, I can directly locate the location of an object, so theoretically we can use hashCode to directly locate the location in the object's hash list, but why is there a key-value pair that uses the hashCode of the key to store data instead of directly storing the value? This is the most important issue related to HashTable performance: Hash conflict!

We know that the conflict is generated because different objects produce the same hash code. If we design an object hash code, we can ensure that 99.999999999% of the hash code is not repeated, however, you cannot avoid an absolute and almost impossible conflict. We know that hashcode returns an int, and its value is only within the int range. What if the data we store exceeds the int range? In this way, two identical indexes will be generated, and two objects will be stored at the index position, so we can use the key itself for judgment. Therefore, for objects with indexes, there are multiple objects at the index position. We must rely on the hashCode of the key and the key itself for differentiation.

HashCode and equals

In Java, the implementation of hashCode is always accompanied by equals. They work closely together. If you design one of them, you need to design another one. Of course, in most cases, these two methods do not need to be considered. Using the default method directly can help us solve many problems. However, in some cases, we must implement it by ourselves to ensure better program operation.

For equals, we must follow the following rules:

Symmetry: If x. equals (y) returns "true", then y. equals (x) returns "true ".

Reflex: x. equals (x) must return "true ".

Analogy: If x. equals (y) returns "true", and y. equals (z) returns "true", then z. equals (x) should also return "true ".

Consistency: If x. equals (y) returns "true", as long as the content of x and y remains unchanged, No matter you repeat x. "true" is returned for the number of equals (y) times ".

In any case, x. equals (null) always returns "false"; x. equals (and x objects of different types) always returns "false ".

For hashCode, we should follow the following rules:

As for the relationship between the two, we only need to remember the following:

If x. equals (y) returns "true", the hashCode () of x and y must be equal.

If x. equals (y) returns "false", the hashCode () of x and y may be equal or different.

After clarifying the relationship above, we will know how they work together. First look:

The entire process is:

1. Determine whether the hashcode of the two objects is equal. If the hashcode is not equal, the two objects are considered unequal. If the hashcode is equal, equals is compared.

2. If the equals of two objects are unequal, the two objects can be considered unequal; otherwise, they are considered equal.

Instance:

Public class Person {private int age; private int sex; // 0: male, 1: Female private String name; private final int PRIME = 37; Person (int age, int sex, string name) {this. age = age; this. sex = sex; this. name = name;}/** omitting the getter and setter Methods **/@ Override public int hashCode () {System. out. println ("Call the hashCode method ........... "); int hashResult = 1; hashResult = (hashResult + Integer. valueOf (age ). hashCode () + Integ Er. valueOf (sex). hashCode () * PRIME; hashResult = PRIME * hashResult + (name = null )? 0: name. hashCode (); System. out. println ("name:" + name + "hashCode:" + hashResult); return hashResult;}/*** override hashCode () */public boolean equals (Object obj) {System. out. println ("Call the equals method ........... "); if (obj = null) {return false;} if (obj. getClass ()! = This. getClass () {return false;} if (this = obj) {return true;} Person person = (Person) obj; if (getAge ()! = Person. getAge () | getSex ()! = Person. getSex () {return false;} if (getName ()! = Null) {if (! GetName (). equals (person. getName () {return false ;}} else if (person! = Null) {return false;} return true ;}}
Public class Main extends JPanel {public static void main (String [] args) {Set <Person> set = new HashSet <Person> (); Person p1 = new Person (11, 1, "Zhang San"); Person p2 = new Person (12, 1, "Li Si"); Person p3 = new Person (11, 1, "Zhang San "); person p4 = new Person (11, 1, "Li Si"); // only p1, p3 System are verified. out. println ("p1 = p3? : "+ (P1 = p3); System. out. println (" p1.equals (p3 )? : "+ P1.equals (p3); System. out. println ("----------------------- split line --------------------------"); set. add (p1); set. add (p2); set. add (p3); set. add (p4); System. out. println ("set. size () = "+ set. size ());}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.