为自定义类实现hashcode和equals [英] Implementing hashcode and equals for custom classes

查看:246
本文介绍了为自定义类实现hashcode和equals的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有很多自定义类,其中也有使用组合的自定义clases。

So I have many custom classes are also have custom clases inside of them using composition.

我的自定义类具有非常频繁变化的变量,我将它们添加到HashSet。所以我的问题是当我实现hashCode
时 - 我应该怎样做一个只有私有字段不断变化的类?

My custom classes have variables that change very frequently and I add them to HashSets. So my question is when I implement hashCode - what should I do for a class that only has private fields that constantly change?

这是一个例子自定义类:

Here is an example of one custom class:

public class Cell {
    protected boolean isActive;
    protected boolean wasActive;

    public Cell() {
    this.isActive = false;
    this.wasActive = false;
    }

    // getter and setter methods...

    @Override
    public int hashCode() {
    // HOW SHOULD I IMPLEMENT THIS IF THIS custom object is constantly
        // being added into HashSets and have it's private fields isActive
        // and wasActive constantly changed.
    }

    // ANOTHER QUESTION Am I missing anything with this below equals implementation?
    @Override
    public boolean equals(Object object) {
    boolean result = false;
    if (object instanceof Cell) {
        Cell otherCell = (Cell) object;
        result = (this.isActive == otherCell.isActive && this.wasActive == 
            otherCell.wasActive);
    }
    return result;
    }


推荐答案

等于和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;
    }

这篇关于为自定义类实现hashcode和equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆