Does that mean Java cannot prevent clients from comparing Pairs with different type arguments?
Yes, but that's the point -- equals
should work with any arbitrary object. What you want would look like
@Override
public boolean equals(Object o)
{
if (o instanceof Pair) {
Pair<?, ?> pair = (Pair<?, ?>) o;
return _1.equals(pair._1) && _2.equals(pair._2);
}
return false;
}
But this should be fine, as long as A
and B
have proper implementations of equals
that take arbitrary Object
s.