Why do I need to override the equals and hashCode

2018-12-30 23:27发布

Recently I read through this Developer Works Document.

The document is all about defining hashCode() and equals() effectively and correctly, however I am not able to figure out why we need to override these two methods.

How can I take the decision to implement these methods efficiently?

29条回答
泛滥B
2楼-- · 2018-12-31 00:16
public class Employee {

    private int empId;
    private String empName;

    public Employee(int empId, String empName) {
        super();
        this.empId = empId;
        this.empName = empName;
    }

    public int getEmpId() {
        return empId;
    }

    public void setEmpId(int empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    @Override
    public String toString() {
        return "Employee [empId=" + empId + ", empName=" + empName + "]";
    }

    @Override
    public int hashCode() {
        return empId + empName.hashCode();
    }

    @Override
    public boolean equals(Object obj) {

        if (this == obj) {
            return true;
        }
        if (!(this instanceof Employee)) {
            return false;
        }
        Employee emp = (Employee) obj;
        return this.getEmpId() == emp.getEmpId() && this.getEmpName().equals(emp.getEmpName());
    }

}

Test Class

public class Test {

    public static void main(String[] args) {
        Employee emp1 = new Employee(101,"Manash");
        Employee emp2 = new Employee(101,"Manash");
        Employee emp3 = new Employee(103,"Ranjan");
        System.out.println(emp1.hashCode());
        System.out.println(emp2.hashCode());
        System.out.println(emp1.equals(emp2));
        System.out.println(emp1.equals(emp3));
    }

}

In Object Class equals(Object obj) is used to compare address comparesion thats why when in Test class if you compare two objects then equals method giving false but when we override hashcode() the it can compare content and give proper result.

查看更多
骚的不知所云
3楼-- · 2018-12-31 00:17

The reason behind this: When your object fields can be null, implementing Object.equals can be a pain, because you have to check separately for null. Using Objects.equal lets you perform equals checks in a null-sensitive way, without risking a NullPointerException. Objects.equal("a", "a"); // returns true Objects.equal(null, "a"); // returns false Objects.equal("a", null); // returns false Objects.equal(null, null); // returns true

查看更多
琉璃瓶的回忆
4楼-- · 2018-12-31 00:19

I was looking into the explanation " If you only override hashCode then when you call myMap.put(first,someValue) it takes first, calculates its hashCode and stores it in a given bucket. Then when you call myMap.put(first,someOtherValue) it should replace first with second as per the Map Documentation because they are equal (according to our definition)." :

I think 2nd time when we are adding in myMap then it should be the 'second' object like myMap.put(second,someOtherValue)

查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 00:22

Because if you do not override them you will be use the default implentation in Object.

Given that instance equality and hascode values generally require knowledge of what makes up an object they generally will need to be redefined in your class to have any tangible meaning.

查看更多
千与千寻千般痛.
6楼-- · 2018-12-31 00:22

When you want to store and retrieve your custom object as a key in Map, then you should always override equals and hashCode in your custom Object . Eg:

Person p1 = new Person("A",23);
Person p2 = new Person("A",23);
HashMap map = new HashMap();
map.put(p1,"value 1");
map.put(p2,"value 2");

Here p1 & p2 will consider as only one object and map size will be only 1 because they are equal.

查看更多
呛了眼睛熬了心
7楼-- · 2018-12-31 00:23

Consider collection of balls in a bucket all in black color. Your Job is to color those balls as follows and use it for appropriate game,

For Tennis - Yellow, Red. For Cricket - White

Now bucket has balls in three colors Yellow, Red and White. And that now you did the coloring Only you know which color is for which game.

Coloring the balls - Hashing. Choosing the ball for game - Equals.

If you did the coloring and some one chooses the ball for either cricket or tennis they wont mind the color!!!

查看更多
登录 后发表回答