How to implement equals for generic pairs?

扶醉桌前 提交于 2019-12-04 14:37:43

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 Objects.

You can not use instanceof like you do due to type erasure. You can only check for instanceof Pair.
Also what is up with that _1 and _2? Really?

vptheron
o instanceof Pair<A, B> 

does not work because generics are not there at runtime, therefore instanceof is not aware of them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!