且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为自定义类实现hashcode和equals

更新时间:2022-11-20 07:40:22

等于和hashCode Java中的契约:



当我们重写equals()方法时,我们必须覆盖hashCode(),Java中的equals方法必须遵循与Java中的hashCode方法的契约如下所述。

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. 如果两个对象等于equals()方法,则哈希码必须与
    相同。

  2. 如果两个对象不等于equals()方法,则哈希码
    可以相同或不同。

这些是您的类的equals和hashcode方法的示例实现:

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;
    }