包含对列表

kal*_*kal 8 java collections

  List<Pair<String, String> > lp = new ArrayList<Pair<String, String> >();
  lp.add(new Pair("1", "2"));
Run Code Online (Sandbox Code Playgroud)

我应该如何检查列表lp是否包含1和2,即对("1","2").

and*_*soj 7

你的Pair班级需要实施equals(),hashCode()而且你们都已经完成了. List.contains()是根据类型的equals()方法实现的.请参阅APIList.contains().(编辑了一下来回应@maaartinus的评论,你的回答你应该读到b/c,观察结果是可靠的,我把它们折叠在这里有点荒谬.正如maaartinus指出的,这里的最佳做法是避免容易出错的手动定义equals和hashcode,而是构建在Guava的helper函数上,用于nullable equalshashCode for n objectss).

final class Pair<T> {

   final T left;
   final T right;

   public Pair(T left, T right)
   {
     if (left == null || right == null) { 
       throw new IllegalArgumentException("left and right must be non-null!");
     }
     this.left = left;
     this.right = right;
   }

   public boolean equals(Object o)
   {
     // see @maaartinus answer
     if (! (o instanceof Pair)) { return false; }
     Pair p = (Pair)o;
     return left.equals(p.left) && right.equals(p.right);
   } 

   public int hashCode()
   {
      return 7 * left.hashCode() + 13 * right.hashCode();
   } 
}
Run Code Online (Sandbox Code Playgroud)

有了合适的equals(),您现在可以:

  lp.add(new Pair("1", "2"));
  assert lp.contains(new Pair("1","2"));
Run Code Online (Sandbox Code Playgroud)

回应下面的评论,或许最好为"我为什么需要实施hashCode()?" 包含一个很好的参考.