繁体   English   中英

使用boolean equals()方法,相同类的两个对象相等

[英]Two objects of the same class being equal using boolean equals() method

有点奇怪的,

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

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

码:

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

检查评论

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM