About the use of hashcode and equals methods in HashSet

The object class is the root class of the class hierarchy, so all classes are the methods of this class first, and the hashcode () and equals () methods are also the methods of this class. 1. Hashcode() method the hashcode() method in the object class is implemented as follows:

public  native  int  hashCode();

Return: the hash value of the object, which can improve the performance of the hash table. HashCode: 1. The hashcode () method is called multiple times by the same object, and the integer is returned. From the execution of one program to another execution of the same program, the integer does not need to be consistent; 2. Using the equals (object) method, if two objects are equal, the hash values returned by the two objects are exactly the same; 3. Using the equals (object) method, two objects are not equal, and the returned hash values may be equal. The hashcode () method and related properties of string in API are excerpted below:

private final char value[];
    private int hash; // Default to 0
    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

Given a string, it is equivalent to executing the construction method:

public String() {
        this.value = new char[0];
}

At this time, the value has been given, and the value under this construction method Length = 0. Obviously, hash = H = 0 (the default value is 0, that is, an empty string). The focus is on the understanding process. For the hash algorithm, just look at the API document.

String s = new String();
System.out.Println(s.HashCode());
结果:0

2. Equals() method the equals() method in the object class is implemented as follows:

public boolean equals(Object obj) {
        return (this == obj);
    }

Indicates whether some other object has the same parameters as this object, and returns true if the parameters are the same, and vice versa. The equals () method implements equality on non empty object references (obj). For any non empty reference value x, x.equals (null) should return false. String and other classes will override the methods in the object class. 3. Class HashSet HashSet is an implementation class of the set interface. You cannot add object values repeatedly. This process is mainly determined by the hash value and the object's equals() method. Use the add() method to add an object of a certain type. / / test the class

package com.test;
//测试类,该类重写了从Object继承而来的HashCode()和equals()方法
public class StudentTest {
    private String name;
    private int age;
    public StudentTest(){}
    public StudentTest(String name,int age){
        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 age){
        this.age = age;
    }
}

//HashSet class

package com.test;

import java.util.HashSet;
import java.util.Set;

public class SetDemo {
    public static void main(String[] args) {
        Set<StudentTest> set1 = new HashSet<>();
        StudentTest s1 = new StudentTest("manu",10);
        StudentTest s2 = new StudentTest("manu",10);
//      set1.add(null);//此处null元素可以使用
        set1.add(s1);
        System.out.println(s1.hashCode());
        set1.add(s2);
        System.out.println(s2.hashCode());
        System.out.println(set1.size());    
    }
}
运行结果:
794284386
779325750
2

S1 and S2 above are two objects. Each time you add an object, the hash value is different, so the object can be added to the HashSet with size = 2. The above involves a problem that the properties of an object are the same. If you don't want to add an object with the same properties again, you must override the hashcode() method and equals() method of studenttest class. After rewriting, the hashes of the two are the same, When using the equals method to verify, it returns true, indicating that the two objects are repeated, and vice versa. The code is as follows:

@Override
    public int hashCode() {
        System.out.println("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) {
        System.out.println("equals");//用于测试
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        StudentTest other = (StudentTest) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

The operation results are as follows:

hashCode
hashCode
3345234
hashCode
equals
hashCode
3345234
1

The attribute values of different objects are the same, but they cannot be added to the HashSet. Pay attention to the changes of requirements. When adding elements to a HashSet, you can add them if the hash values are inconsistent; If the hash values are the same, call the equals method to see if the objects are the same. If they are different (false), they can be added. Note that equals judges that if two objects are different, the hash values may be the same. In the above example, the hash values are the same, but S1 and S2 are two different objects.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>