Implementing hashcode and equals for custom classes

巧了我就是萌 提交于 2019-12-01 06:35:52

Equals and hashCode contract in Java:

We must override hashCode() when we override equals() method, equals method in Java must follow its contract with hashCode method in Java as stated below.

  1. If two objects are equal by equals() method then there hashcode must be same.
  2. If two objects are not equal by equals() method then there hashcode could be same or different.

These are sample implementation of equals and hashcode methods for your class:

 //Hashcode Implementation    

   @Override
    public int hashCode() 
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + (isActive ? 1231 : 1237);
        result = prime * result + (wasActive ? 1231 : 1237);
        return result;
    }

//equals Implementation    
    @Override
    public boolean equals(Object obj) 
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Cell other = (Cell) obj;
        if (isActive != other.isActive)
            return false;
        if (wasActive != other.wasActive)
            return false;
        return true;
    }

You are SOL. Where hashCode() is used in a key in standard Java collections, it should not change. Or else you need a custom HashSet-like implementation.

Use only non-changing fields (or, if you are daring and don't mind occasional crashes, very rarely changing fields) to calculate hashCode().

(Added). In your particular example, use Object.hashCode().

(Added #2) Even if your Cell class were immutable (the two booleans didn't change) it makes a poor choice for hashing, because it only has 2 bits of range. Imagine hashing all people by whether they are male/female and blue eyes / brown eyes. A very good start, but there's only 4 categories, and there will be like 2 billion people in each one. Ideally, you'd have several other categories, like year of birth, country of birth, etc.

Veera

Here is the example of class which has private fields.

public class Test {

    private int num;
    private String data;

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if ((obj == null) || (obj.getClass() != this.getClass()))
            return false;
        // object must be Test at this point
        Test test = (Test) obj;
        return num == test.num
                && (data == test.data || (data != null && data
                        .equals(test.data)));
    }

    public int hashCode() {
        int hash = 7;
        hash = 31 * hash + num;
        hash = 31 * hash + (null == data ? 0 : data.hashCode());
        return hash;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!