user1257724
user1257724

Reputation:

Checking the specific type of object of an argument with type "Object"

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

Answers (3)

if(!(o instanceof Tuple))
    return false;
Tuple other = (Tuple) o;
...

Upvotes: 3

Juned Ahsan
Juned Ahsan

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

gerrytan
gerrytan

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

Related Questions