我只是想在客户列表中找到一个对象的位置,尽管在我使用equals()
方法时它会不断返回false。
我现在明白你必须创建自己的equals
方法来覆盖自动方法,但是当我在Customer
内进行比较时,我无法理解如何创建一个方法。 1}}数组。
以下是我的实例变量:
Customer
这是我找到对象位置的方法:
private Customer[] data;
private int size;
private final static int INITIAL_SIZE = 20;
(没有找到返回的地点)
我正在尝试重写public int findCustomerLocation(String name)
{
int spot = -1;
Customer cus = new Customer(name);
for(int i = 0; i < size ; i++)
{
if((data[i].equals(cus)))
{
spot = i;
System.out.println("spot is:" + spot);
}
else
{
System.out.println("spot not found");
}
}
return spot;
}//findCustomerLocation
方法,但我有点卡住了,如果它是另一个的实例,我正在尝试使用它,但它仍然会返回false
答案 0 :(得分:1)
您的equals
方法只使用相同的身份运算符(==
)作为默认Object#equals()
。据推测,当Customer
个对象内部的某些特定信息(例如ID字段)相等时,您打算将它们视为相等。如果是这样,您需要比较equals()
中的这些字段(并且应始终在equals()
中包含hashCode()
中涉及的每个字段。)
这样的事情可能就是你想要的:
public boolean equals(Object other) {
if(!other instanceof Customer) {
return false;
}
Customer that = (Customer) other;
return this.name.equals(that.name);
}
答案 1 :(得分:0)
equals
方法应该实现指示给定对象是否“等于”当前(this)对象的逻辑。从逻辑上讲,它不应该依赖于非类成员的字段或参数。在您的情况下,您不应该使用data
数组或size
方法中的equals
字段。只需在Customer
的相应字段中添加检查。
例如,假设Customer
有一个名为name
的字段,那么以下equals
会检查两个Customer
是否相等,如果它们具有相同的name
}:
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Customer other = (Customer) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
如果您使用的是像Eclipse这样的IDE,则可以使用快捷方式以一致的方式自动覆盖equals()
和hashCode()
方法。通常,两个方法都应该使用相同的类成员,这样如果两个对象相等,则它们的哈希码值是相同的。
答案 2 :(得分:0)
您正在比较Customer
个对象,而不是它们的名称。由于它们不是同一个对象,equals()
将返回false。要解决此问题,请将以下代码添加到Customer
:
public boolean equals(Object obj){
if(obj instanceof Customer){
Customer c = (Customer)obj;
if(c.name.equals(this.name)
return true;
}
return false;
}
祝你好运!编辑:对于重复的帖子感到抱歉,请查看chrylis的帖子,并在
obj != null
语句前插入instanceof
答案 3 :(得分:-1)
请注意,实施hashCode
时必须实施equals
。有一些things to consider可以正确地编写这些方法。为了安全起见,最好让IDE生成这些方法。例如,在Eclipse中,转到 Source&gt;生成hashCode()和equals()...