Just for fun, I'm trying to implement a generic Pair class in Java. I'm having trouble with equals
:
public class Pair<A, B>
{
public final A _1;
public final B _2;
// ... unnecessary details left out ...
public boolean equals(Pair<A, B> that)
{
return (_1.equals(that._1)) && (_2.equals(that._2));
}
@Override
public boolean equals(Object o)
{
return (o instanceof Pair<A, B>) && equals((Pair<A, B>) o);
}
}
However, o instanceof Pair<A, B>
does not seem to work. Why is that?
Using (o instanceof Pair) && equals((Pair<A, B>) o)
gives me a warning for the cast. Getting rid of the <A, B>
part on the cast still gives me a warning, which I guess also some sense.
Does that mean Java cannot prevent clients from comparing Pairs with different type arguments?