When a Java custom object is used as the key of the Map, the equals() and hashCode() methods need to be rewritten

  A Java Class is customized in the project, named Student, with attributes stuNm (name) and age (age). There is a scenario where the object is used as the key and the score is stored as the value in the Map, and then the score is retrieved based on the student object. As long as the name and age are the same, they are considered the same student.
  For the access value in the Map, it is based on the hashCode value of the key and stored in the corresponding bucket after calculation (before Java 8). In the above scenario, when the student object is used as the key of the Map, the hashCode and equals methods need to be rewritten. When the stuNm and age are the same, the object is considered equal and the hashCode value is equal.
  For how to quickly generate equals() and hashCode() methods, see "IDEA Quickly Override the equals() and hashCode() methods for Java Class" . The Student class and the rewritten equals() and hashCode() methods are shown below.

package com.test.model;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Student {
    
    

    // 姓名
    private String stuNm;

    // 年龄
    private String age;

    // 构造函数
    public Student(String stuNm, String age) {
    
    
        this.stuNm = stuNm;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
    
    
        if (this == o) return true;
        if (!(o instanceof Student)) return false;

        Student student = (Student) o;

        if (stuNm != null ? !stuNm.equals(student.stuNm) : student.stuNm != null) return false;
        return age != null ? age.equals(student.age) : student.age == null;
    }

    @Override
    public int hashCode() {
    
    
        int result = stuNm != null ? stuNm.hashCode() : 0;
        result = 31 * result + (age != null ? age.hashCode() : 0);
        return result;
    }
}

  The test method is shown below.

package com.test.model;

import java.util.HashMap;
import java.util.Map;

public class Test {
    
    

    public static void main(String[] args) {
    
    

        Map<Student, String> map = new HashMap<>();

        Student stuA = new Student("张三", "20");
        map.put(stuA, "95");

        Student stuB = new Student("张三", "20");
        map.put(stuB, "93");

        System.out.println(map.get(stuA));      // 93
        System.out.println(map.get(stuB));      // 93

        Student stuC = new Student("张三", "20");
        System.out.println(map.get(stuC));      // 93
        System.out.println(stuA.equals(stuC));  // true
    }
}

  The different student objects are named Zhang San and their age is 20. Because equals() and hashCode() are rewritten, they are considered to be the same key when the put() and get() operations of Map are performed. The value is 93.

Guess you like

Origin blog.csdn.net/piaoranyuji/article/details/107840476