0

Bit of a strange one,

I actually have managed to answer a question by looking at examples and messing with my code but I don't actually understand fully how it is working!

Any explanation would be great and much appreciated!

Code:

I have a class called Player and 3 objects being created in another class in the main method.

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 回答