Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the equals method in java

Tags:

java

This is my implementation of the equals class for a Coor class which is just contains 2 ints x and y. would this be the proper way of implementing this method?

 public boolean equals(Object obj) {
        if (obj == null || obj.getClass() != this.getClass()) {
            return false;
        }
        Coor temp = (Coor) obj;
        if (temp.x == this.x && temp.y == this.y) {
            return true;
        } else {
            return false;
        }
    }
like image 765
user979490 Avatar asked Oct 05 '11 00:10

user979490


People also ask

What is the default implementation of equals method Java?

Shallow comparison: The default implementation of equals method is defined in Java. lang. Object class which simply checks if two Object references (say x and y) refer to the same Object. i.e. It checks if x == y.

What is equals () method in Java?

Java String equals() Method The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.


1 Answers

You could add one more check for reflexive equality (equal to self):

 public boolean equals(Object obj) {

    // Reflexive equality: did I get passed myself?
    if(this == obj){
        return true;
    }

    if (obj == null || obj.getClass() != this.getClass()) {
        return false;
    }

    Coor temp = (Coor) obj;
    return temp.x == this.x && temp.y == this.y;
}
like image 198
Pat Avatar answered Sep 27 '22 23:09

Pat