【问题标题】:Two objects of the same class being equal using boolean equals() method使用 boolean equals() 方法相同类的两个对象相等
【发布时间】:2013-10-27 20:20:36
【问题描述】:

有点奇怪,

我实际上已经通过查看示例和弄乱我的代码来回答一个问题,但我实际上并不完全理解它是如何工作的!

任何解释都会非常好,非常感谢!

代码:

我有一个名为 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;
    }
}

【问题讨论】:

  • 实例Player真的应该是小写的...
  • 如果objPlayer子类,这也将返回true,并且它具有相同的getName。有时我将其视为if (obj != null && obj.getClass() == this.getClass()) 而不是if (obj instanceof Player),以确保对象确实具有相同的类型。

标签: java boolean return equals


【解决方案1】:

检查cmets

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
    }
}

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多