我正在尝试覆盖 Java 中的 equals 方法。我有一个类 People
它基本上有 2 个数据字段 name
和 age
。现在我想覆盖 equals
方法,以便我可以检查 2 个 People 对象。
我的代码如下
public boolean equals(People other){
boolean result;
if((other == null) || (getClass() != other.getClass())){
result = false;
} // end if
else{
People otherPeople = (People)other;
result = name.equals(other.name) && age.equals(other.age);
} // end else
return result;
} // end equals
但是当我写 age.equals(other.age)
它给了我错误,因为equals方法只能比较字符串并且年龄是整数。
解决方案
我按照建议使用 ==
运算符,我的问题就解决了。
原文由 user702026 发布,翻译遵循 CC BY-SA 4.0 许可协议
输出: