问题描述
我正在尝试覆盖将对象作为输入的equals()方法。
我在同一个程序包中有以下课程
public class Herd{
int count;
boolean exists;
在覆盖该方法的类中,我试图比较Object是否与位置,等级以及它们是否属于同一类的变量匹配
public class Animal{
private Herd lot;
private int rank;
public boolean equals(Object animl) {
if(this.getClass() == animl.getClass() && this.rank == animl.rank && this.lot == animl.**lot**) {
return true;
}
return false;
}
我知道要进行比较,我将使用具有所有这些参数的对象,但是,它在Animal类本身中会说
for animl.rank "rank cannot be resolved or is not a field"
for animl.lot "lot cannot be resolved or is not a field"
我尝试向下转换,即(... ==(Animal)animl.rank),但这给了我一个不兼容的操作数类型错误。我也尝试将等级转换为int,但这给了我上述问题。
任何帮助表示赞赏。
解决方法
您需要正确地投射animl
对象:
public boolean equals(Object animl) {
if(this.getClass() == ((Animal) animl).getClass() && this.rank == ((Animal) animl).rank && this.lot == ((Animal) animl).lot) {
return true;
}
return false;
}
我认为最好使用equals
而不是=
:
public boolean equals(Object animl) {
if(this.getClass() == ((Animal) animl).getClass() && this.rank.equals( ((Animal) animl).rank) && this.lot.equals( ((Animal) animl).lot)) {
return true;
}
return false;
}
,
尝试一下:
private Herd lot;
private int rank;
public boolean equals(Object animl) {
if(!(animl instanceof Animal))) {
return false;
}
Animal an = (Animal)animl;
return this.rank == an.rank && this.lot == an.lot;
}
您可能需要这些属性的吸气剂。我没有进行任何编译或测试。
,类equals
中的方法Animal
应该这样重写:
- 检查null和类是否相等
- 投射对象以与
Animal
进行比较 - 比较
Animal
类的字段,请注意将equals
用于Herd
public class Animal {
// ...
@Override
public boolean equals(Object o) {
if (o == null || this.getClass() != o.getClass()) {
return false;
}
if (this == o) return true;
Animal animal = (Animal) o;
return this.rank == animal.rank &&
this.lot != null && this.lot.equals(animal.lot);
}
}
类似地,方法equals
可能需要在Herd
中被覆盖:
public class Herd {
// ...
@Override
public boolean equals(Object o) {
if (o == null || this.getClass() != o.getClass()) {
return false;
}
if (this == o) return true;
Herd herd = (Herd) o;
return this.count == herd.count && this.exists == herd.exists;
}
}
,
比较无法通过这种方式进行。 消息:
for animl.rank "rank cannot be resolved or is not a field"
for animl.lot "lot cannot be resolved or is not a field"
是正确的,因为在Object类中没有这样的属性。它们仅存在于您的动物类中。
也就是说,在进行实际比较之前,需要将对象显式转换为动物。试试这个:
public class Animal{
private Herd lot;
private int rank;
public boolean equals(Object animl) {
Animal animal = (Animal) animl;
if(this.getClass() == animal.getClass() && this.rank == animal.rank && this.lot == animal.lot) {
return true;
}
return false;
}
请注意,您可能需要对this.lot == animal.lot