有点奇怪,
我实际上已经设法通过查看示例并弄乱我的代码来回答问题,但我实际上并不完全理解它是如何工作的!
任何解释都会很棒,非常感谢!
代码:
我有一个叫做Player的类,在main方法的另一个类中创建了3个对象。
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj instanceof Player) {
Player player = (Player) obj;
if (player.getName().equals(this.getName())) {
return true;
} else {
return false;
}
} else {
return false;
}
}
答案 0 :(得分:2)
检查评论
public boolean equals(Object obj) {
if (this == obj) { // if the references are the same, they must be equal
return true;
} else if (obj instanceof Player) {
Player player = (Player) obj; // we cast the reference
if (player.getName().equals(this.getName())) { // we compare the name
return true; // they are equal if names are equal
} else {
return false; // otherwise, they aren't
}
} else {
return false; // if the target object isn't of the type you want to compare, we choose to say it is not equal
}
}