【发布时间】:2018-08-27 11:21:58
【问题描述】:
我正在从事一个小项目,其中有国家、人口和大陆等类别。
Population 和 Continent 类都使用枚举来定义可能的值。我想在哪个国家/地区使用“工厂方法”来创建新国家/地区。代码如下:
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:
等于:
但不是。
我在网上看,我发现当给定相同的参数时,它应该知道它是相同的,例如对于相同的参数,不应有两个不同的对象。我确定我是否理解正确,但它似乎是相关的。
我仍然不知道是否是这种情况以及如何处理它。想法?
更新:
在出现一些建议后,我尝试将 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;
}
它不允许我做 .population 和 .continent
【问题讨论】:
-
这些要比较的对象是如何创建的?
-
不要在人口上使用
==,在那里也使用equals。并在人口对象上实现等于。当你使用==时,表示对象必须相同不相等。 -
equals的签名应该是'equals(Object o)' ??
-
@bilak 你可以在
enum上使用== -
@RobAu 你是对的,我没有意识到这是一个枚举
标签: java