Reasons for overriding hashcode methods

Asked 2 years ago, Updated 2 years ago, 96 views

Why do you override hashcode methods in Java?

java hashcode

2022-09-22 22:15

1 Answers

I'll give you an example where the hashcode method needs to be overridden. First, if the two objects are the same, the values for each hashCode of the two objects must be the same.

public class Student {
    private int student_id;
    private String name;
    private String major;

    public Student(int id, String n, String m){
        student_id = id;
        name = n;
        major = m;
    }

    public int getStudent_id() {
        return student_id;
    }
    public void setStudent_id(int student_id) {
        this.student_id = student_id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
}

If you use this class with HashMap when you have a Student class like this,

Map<Student,String> m = new HashMap<Student,String>();
m.put(new Student (20113263,"Kim Sung-kook,"Computer Science"), "Sean");

When you type it like this, m.Calling get(20113263,"Kim Sung-kook,"Computer Science") will likely return "Sean" but will actually return null. The reason for this is that we do not override the hashcode, so the two instances have the same hashcode value. Therefore, the instance you search for with the get method will find the Student in a different bucket than the instance you saved in the put method. This problem can be solved simply by overriding the hashCode.

Then, how should I override hashCode?

The worst hashcode is @Override public int hashCode(){return 42;} This is what it looks like. This is the worst form in which all objects have the same hash value, even though they are legitimate in a way. All objects are in the same bucket Collisions continue to occur every time you add them, resulting in a linear structure by connecting buckets to linked lists, resulting in tremendous slow navigation and insertion and deletion.

A good hashCode method is recommended to distribute different objects as evenly as possible at hash values.


2022-09-22 22:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.