About the hashcode problem in Java

Source: Internet
Author: User

1. HashSet Collection storage data structure (hash table) 1.1 What is a hash table?

The bottom of the hash table is also the array mechanism, the array also holds the object, and these objects are placed in the array in the location of the special, when the need to put these objects to the array, then according to the specific data of these objects combined with the corresponding algorithm, the object in the array to calculate the position, and then put this object in the array. And such an array is called a hash array, that is, a hash table.

1.2 Hash table storage data structure principle

When storing elements in a hash table, it is necessary to combine the corresponding algorithm according to the unique data of the element, which is actually the Hashcode method in the object class. Because any object is a subclass of the object class, any object also has this method. That is, when the object is stored in the hash table, it calls the object's Hashcode method, calculates where the object is stored in the table, it is important to note that if the two object Hashcode method calculates the result, this phenomenon is called the hash conflict, then the object's Equals method is called. Comparing the two objects is not the same object, if the Equals method returns True, then the second object will not be stored in the hash table, if the return is false, this value will be stored in the hash table.

1.3 Hash Table storage data structure schematic diagram

2. Hash

Hash is the meaning of hashing, that is, the arbitrary length of the input, through the hash algorithm to transform into a fixed-length output, the output is the hash value. There are several key conclusions about the hash value:

    1. If there is a record in the hash table that is K equal to the original input, then the K f(K) storage location must be

    2. Different keywords may get the same hash address after the hash algorithm transformation, which is called collision

    3. If the two hash values are different (assuming the same hash algorithm), then the original input corresponding to the two hash values must be different

3. Hashcode
    1. The existence of hashcode is primarily for the purpose of finding the shortcut, and hashcode is used to determine the storage address of the object in the hash storage structure.

    2. If two objects equals equal, then the hashcode of the two objects must be the same

    3. If the object's Equals method is overridden, then the object's Hashcode method is also rewritten as much as possible

    4. If the hashcode of two objects is the same, it does not mean that two objects are the same, only the two objects in the hash storage structure, stored in the same location

    5. If two objects are not equal according to the Equals method, calling the Hashcode method on any of these two objects does not necessarily produce a different integer result. However, programmers should be aware that generating different integer results for unequal objects can improve the performance of the hash table.

4. Hashcode Effect

We know that the elements inside the set cannot be duplicated, so how do we do that?

Set is based on the Equals () method to determine whether two elements are equal. Let's say that there are already 1000 elements in the set, so when the 1001th element comes in, it is possible to call the Equals method up to 1000 times, and if the Equals method is more complex and contrasting, then the efficiency will be greatly reduced. Using Hashcode is not the same, for example HashSet, the bottom is based on HASHMAP implementation, first through the hashcode to take a mold, so suddenly fixed to a position, if there is no element in this position, Then you can be sure that there is no element in the hashset and the newly added elements of the equals, you can directly store, do not need to compare; if there are elements in this position, compare each other, compare the time to compare Hashcode,hashcode are different, Certainly not the same, hashcode equal, then equals, no same element exists, there is no same element is not saved. If the original set has the same elements, as long as the Hashcode generation method is well defined (not duplicated), regardless of how many elements in the original set, only need to execute once equals. As a result, the number of actual calls to the Equals method is greatly reduced, increasing efficiency.

5. HashSet storage of type elements in Javaapi

When you store the type elements provided in Javaapi in HashSet, you do not need to override the hashcode and equals methods of the elements, because both methods have been rewritten in each of the JAVAAPI classes, such as the String class, the integer class, and so on.

Give me a chestnut:

public class HashSetDemo {    public static void main(String[] args) {        //创建HashSet对象        HashSet<String> hs = new HashSet<String>();        //给集合中添加自定义对象        hs.add("zhangsan");        hs.add("lisi");        hs.add("wangwu");        hs.add("zhangsan");        //取出集合中的每个元素        Iterator<String> it = hs.iterator();        while(it.hasNext()){            String s = it.next();            System.out.println(s);        }    }}

Output Result:

Wangwu
Lisi
Zhangsan

6. HashSet Store Custom type elements

When you store a custom type element in HashSet, you need to override the hashcode and Equals methods in the object to establish your own comparison to ensure that the objects in the HashSet collection are unique

Give me a chestnut:

Custom Student Class

public class Student {private String name;    private int age;        Public Student (String name, Int. age) {super ();        THIS.name = name;    This.age = age;    } public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public int Getage () {return age;    public void Setage (int.) {this.age = age;    } @Override Public String toString () {return ' Student [name= + name + ", age=" + Age + "]";        } @Override public int hashcode () {final int prime = 31;        int result = 1;        result = Prime * result + age;        result = Prime * result + ((name = = null)? 0:name.hashcode ());    return result;        } @Override public boolean equals (Object obj) {if (this = = obj) return true; if (! (            obj instanceof Student) {System.out.println ("type error");        return false;  } Student other = (Student) obj;      return this.age = = Other.age && this.name.equals (other.name); }}

Create HashSet collection, store student objects

public class HashSetDemo {    public static void main(String[] args) {        //创建HashSet对象        HashSet<Student> hs = new<Student> HashSet();        //给集合中添加自定义对象        hs.add(new Student("zhangsan",21));        hs.add(new Student("lisi",22));        hs.add(new Student("wangwu",23));        hs.add(new Student("zhangsan",21));        //取出集合中的每个元素        Iterator it = hs.iterator();        while(it.hasNext()){            Student s = (Student)it.next();            System.out.println(s);        }    }}

Output Result:

Student [Name=lisi, age=22]
Student [Name=zhangsan, age=21]
Student [Name=wangwu, age=23]

7. Write in the back

The only thing that guarantees the HashSet collection element is that it is determined by the object's hashcode and the Equals method. If we store the custom object in the collection, then we must override the Hashcode and the Equals method to establish a comparison of the current object, so that it is unique.

About the hashcode problem in Java

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.