6

I am getting the following code snippet from Android's Pair.java

public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof Pair)) return false;
    final Pair<F, S> other;
    try {
        other = (Pair<F, S>) o;
    } catch (ClassCastException e) {
        return false;
    }
    return first.equals(other.first) && second.equals(other.second);
}

I was wondering, how is it possible to have ClassCastException, after instanceof returns true.

6
  • 1
    check your import. Maybe you are importing two different Pair class Commented Sep 25, 2012 at 14:09
  • 1
    Looks impossible. Post full code sample. Commented Sep 25, 2012 at 14:13
  • You aren't getting a ClassCastException, are you? It should be impossible in this case. Just because you found code somewhere that catches some random exception doesn't mean this exception can actually be thrown. Commented Sep 25, 2012 at 14:33
  • It's possible your F and/or S class is the one throwing the ClassCastException. Post full code sample or a stack trace, please. Commented Sep 25, 2012 at 14:47
  • Full code is already posted as external link in the question. That's the official code from Android Commented Sep 25, 2012 at 15:22

1 Answer 1

4

It isn't possible. The code makes no sense. Whoever wrote it probably didn't understand that F and S are erased at runtime so a ClassCastException could never happen.

Sign up to request clarification or add additional context in comments.

2 Comments

The code are from Google Android engineers. Possible they see something we don't notice?
Same guess from me. Anyone can go wrong, including Googlers :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.