Please tell me what object is used to redefine equals in HashMap.

Asked 1 years ago, Updated 1 years ago, 483 views

java

package sec01.verify.exam03;

public class Student {

private String studentNum;

public Student(String studentNum) {
    this.studentNum = studentNum;
}

public String getStudentNum() {
    return studentNum;
}

@Override
public boolean equals(Object obj) {
    if(obj instanceof Student) {
        Student student = (Student) obj;
        if(studentNum.equals(student.getStudentNum())) {
            return true;
        }
    }
    return false;
}

@Override
public int hashCode() {
    return studentNum.hashCode();
}

}

===============================================================

package sec01.verify.exam03;

import java.util.HashMap;

public class StudentExample {

public static void main(String[] args) {
    //Create a HashMap object that stores the total score with the Student key
    HashMap<Student, String> hashMap = new HashMap<Student, String>();

    //Save the score 95 of the new Student ("1")
    hashMap.put(new Student("1"), "95");

    //Read score with new Student ("1")
    String score = hashMap.get(new Student("1"));
    System.out.println("Total score of student #1:" + score);

}

}

If hashMap is a pair of keys and values, the keys cannot be duplicated and are the same key. I understand that the old one is gone and only the new key is left. And when you use it, you compare hash codes first and then you compare equals...

Here's the question. In the code above, @Override What does Object obj specifically include in public boolean equals (Object obj)? Object is the top class, so all classes can be included, but I don't know what's in it.

java hashmap object

2023-02-05 15:24

1 Answers

Why equals contains Object is also related to the design of the language Java.

Equals in HashMap only needs to be compared with Student and Student, but not equals but equalsHere's why /code> needs to be woven.

So the bottom line is, equals itself is, as you said, "You can fit anything." For this reason, a line like if (obj instance of Student) in equals is a frequent pattern.

I don't know what obj is, but if obj instance of Student is false, it means that the data types of this and obj are different, so please return false. You only need to compare the values of the two objects and return the comparison results if they have the same datatype.


2023-02-05 15:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.