0

ちょっと変わった、

私は実際に例を見て自分のコードをいじることで質問に答えることができましたが、実際にはそれがどのように機能するかを完全には理解していません!

どんな説明も素晴らしく、大歓迎です!

コード:

Player というクラスがあり、メイン メソッドの別のクラスで 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;
    }
}
4

1 に答える 1

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
    }
}
于 2013-10-18T21:05:09.860 に答える