How can I get a ClassCastException after instanceof returns true

I get the following code snippet from Android 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 to get a ClassCastException after it instanceofreturns true.

+5
source share
1 answer

It's impossible. The code does not make sense. The one who wrote this probably didn’t realize that Fthey are Serased at runtime, so it ClassCastExceptionwill never happen.

+3
source

All Articles