如何为泛型对实现equals? [英] How to implement equals for generic pairs?

查看:226
本文介绍了如何为泛型对实现equals?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了好玩,我试图在Java中实现一个通用的Pair类。我在等于时遇到问题:

  public class Pair< A ,B> 
{
public final A _1;
public final B _2;

// ...不必要的细节遗漏了...

public boolean equals(Pair< A,B>)
{
return (_1.equals(that._1))&& (_2.equals(that._2));
}

@Override
public boolean equals(Object o)
{
return(o instanceof Pair< A,B>)&& ((Pair )o);
}
}

然而, o instanceof Pair< ; A,B> 似乎不起作用。为什么会这样?



使用(o instanceof Pair)&& equals((Pair )o)给我一个演员的警告。摆脱演员阵容上的< A,B> 部分仍然给我一个警告,我想这也是有道理的。



这是否意味着Java无法阻止客户端将对与不同的类型参数进行比较?

解决方案

这是否意味着Java不能阻止客户将对与不同类型参数进行比较?


是的,但这就是要点 - equals 应该可以处理任意的对象。你想要什么样子?/ b>

  @Override 
public boolean equals(Object o)
{
if(o instanceof Pair){
Pair <?,?> pair =(Pair <α,β>)o;
return _1.equals(pair._1)&& _2.equals(pair._2);
}
返回false;
}

但这应该没问题,只要 A B 具有正确的等于的实现,它们取任意 Object s。


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?

解决方案

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.

这篇关于如何为泛型对实现equals?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆