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;
}
}
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With