java equals()没有给出预期的结果
我正在做一个小项目,在那里我有国家、人口和大陆课程
人口和大陆这两个类都使用枚举来定义可能的值。在中国,我想用“工厂方法”来创造新的国家。代码如下:
public enum Continent {
EUROPE,
ASIA,
AMERICA;
}
public enum Population {
LOW(1000000),
AVERAGE(2000000),
HIGH(5000000);
}
public class Country{
private Continent=null;
private Population=null;
Country(Continent continent, Population population){
this.continent=continent;
this.population=population;
}
好吧,我的问题是我试图重写我的equals()函数,但它没有给出预期的结果
public boolean equals(Country other){
if(this.population == other.population && this.continent==other.continent)
return true;
else
return false;
}
但是断言测试给出了以下结果
java.lang.AssertionError: [new Country(Europe,HIGH)] Expecting:
<"Romania (Country@464a7b61)"> to be equal to: <"Romania (Country@488d8dd8)">
but was not.
我在网上搜索,发现当给定相同的参数时,它应该知道它是相同的,例如,对于相同的参数,不应该有两个不同的对象。我确信我是否正确理解了它,但它似乎是相关的
我仍然不知道情况是否如此,以及如何处理。想法
更新:
在一些建议出现后,我尝试将equals函数改为
public boolean equals(Country other){
if(this.population.equals(other.population) && this.continent.equals(other.continent))
return true;
else
return false;
}
更新2:
public boolean equals(Object o){
if(this.population.equals(o.population) && this.continent.equals(o.continent))
return true;
else
return false;
}
它不允许我做。人群和。大陆
# 1 楼答案
你的
equals()
方法的签名错误应该是:
注意
Object o
而不是Country
# 2 楼答案
除了其他答案指出的签名更改之外,您还需要检查参数是否为
Country
类型。只有当它是你可以访问它的属性。下面的代码执行此操作:# 3 楼答案
关于面向对象编程的一些基础知识:
当您从一个类(例如
Object
)派生,并且希望重写super
类中的一个方法时,您需要匹配该方法的签名。在你的例子中,你覆盖了Object::equals
,所以你需要匹配它的签名正如@RobAu所写,这是
这反过来意味着您的编译器将不允许您使用访问子类的任何成员。这就是为什么你需要(a)检查论点的类别,以及(b)对
Country
进行一次硬转换作为替代方案,您可以使用Lombok这样的库,它将为您生成一个典型的equals/hash组合(参见https://projectlombok.org/features/EqualsAndHashCode)
快乐编码