Reputation:
public class Tuple {
// ...
// ...
// ...
// Compare if Tuple is equal to specified object o
public boolean equals(Object o) {
// code goes here
}
// ...
}
I have a Tuple class for Tuple objects and one of the methods is to check if an object is equal to a Tuple object. I won't specify what determines equality between two Tuples, but what I'm confused about is how to deal with the fact that the parameter argument for the equals() method is an 'Object'. Obviously, if the object is not even a Tuple, I return false--what is the best way to do this?
I know there are methods such as instanceof and getClass, but is the correct/recommended way to do this?
Thanks!
Upvotes: 0
Views: 59
Reputation: 77226
if(!(o instanceof Tuple))
return false;
Tuple other = (Tuple) o;
...
Upvotes: 3
Reputation: 68715
You need to cast the object o
to Tuple
to compare the attributes of Tuple
. You should compare whether the input object is of type Tuple
using instanceOf
operator before casting.
Upvotes: 0
Reputation: 41143
You have to review your business requirement, but in most cases if the type is different then it will be deemed inequal -- you can't even compare other object unless it's the same type / subtype. Hence:
public boolean equals(Object o) {
if(! (o instanceof Tuple)) return false;
Tuple other = (Tuple) o;
// do your comparison logic here
}
Upvotes: 0