【问题标题】:Java hashCode, equals error i don't understand [duplicate]Java hashCode,等于错误我不明白[重复]
【发布时间】:2021-12-17 03:10:06
【问题描述】:

我必须在我的班级中重写 hashCode 方法,但我有这个错误:

找不到符号:符号:变量对象

另外,我如何在 equals 中添加字符串发明者比较 我的代码:

public abstract class ThingMadeByHuman {

    protected String inventor;
    protected int yearOfInvention;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o != null || getClass() != o.getClass()) {
            return false;
        }
        ThingMadeByHuman thingMadeByHuman = (ThingMadeByHuman) o;
        return Integer.compare(thingMadeByHuman.yearOfInvention, yearOfInvention) == 0;
    }

    @Override
    public String toString() {
        return "ThingMadeByHuman: inventor:" + this.inventor + " yearOfInvention:" + this.yearOfInvention;
    }

    @Override
    public int hashCode() {
        return Objects.hash(yearOfInvention) + super.hashCode();
    }

    public ThingMadeByHuman(String inventor, int yearOfInvention) {
        this.yearOfInvention = yearOfInvention;
        this.inventor = inventor;
    }
}

【问题讨论】:

    标签: java overriding hashcode


    【解决方案1】:

    您可能需要导入Objects 类。请参阅 Java docs。请参阅 Oracle 的 tutorial

    import java.util.Objects ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      • 2017-10-01
      • 1970-01-01
      • 2018-05-22
      • 2010-09-16
      • 2016-10-09
      • 1970-01-01
      相关资源
      最近更新 更多