Reputation: 280
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;
}
}
Upvotes: 5
Views: 1212
Reputation: 308763
There's only one source to read for how to override equals and hashCode: chapter 3 of Joshua Bloch's "Effective Java".
If you have a good IDE, like IntelliJ, it'll generate equals and hashCode the right way for you.
Upvotes: 0
Reputation: 25675
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;
}
Upvotes: 7
Reputation: 2561
I believe this would work, at a quick glance. I say this because:
This question has certainly been asked many times before though. See here: Overriding equals and hashCode in Java. A book called Effective Java discusses this topic in great detail too, and the particular chapter is linked off of there.
Upvotes: 0
Reputation: 19270
Here’s a more straightforward way:
public boolean equals(Object other) {
return other instanceof Coor
&& ((Coor) other).x == x
&& ((Coor) other).y == y
}
Upvotes: 0
Reputation: 2888
Check this out:
http://www.javapractices.com/topic/TopicAction.do?Id=17
If that article is too much detail, then the short of it is: Your implementation is correct, but you should keep some other things in mind:
You will also have to implement hashCode.
equals will no longer commpare the object's identity. Doesn't sound like that's a problem for you.
You could add the @Override annotation to your equals method.
Upvotes: 1
Reputation: 15990
Seems ok. For brevity sake, you can do:
return temp.x == this.x && temp.y == this.y
Instead of
if (temp.x == this.x && temp.y == this.y) {
return true;
} else {
return false;
}
Also, please keep in mind the Object Contract (seriously!).
See the accepted answer here: What issues should be considered when overriding equals and hashCode in Java?
This can save you a huge about of headache in the future.
Upvotes: 3
Reputation: 62769
Yes, it would.
Also be sure to override your hashCode() method--never override one without doing the other as well, it will confuse the hell out of your collections.
Your case could use a hash where it simply shifts one of the ints 32 bits and adds it to the other creating a completely unique long (a perfect hash function in this case--no collisions)
Upvotes: 5