List<Pair<String, String> > lp = new ArrayList<Pair<String, String> >();
lp.add(new Pair("1", "2"));
我应该如何检查列表 lp 是否包含 1 和 2,即 Pair ("1", "2")。
最佳答案
您的Pair
类需要实现equals()
和hashCode()
并且您已准备就绪。 List.contains()
是根据类型的 equals()
方法实现的。查看API for List.contains()
. (对来自@maaartinus 的评论进行了一些编辑,你应该阅读他的回答 b/c 观察结果是可靠的,我把它们折叠在这里有点荒谬。正如 maaartinus 指出的那样,这里的最佳实践是避免容易出错的 equals 和 hashcode 手动定义,而是建立在 Guava 的 nullable equals 和 hashCode for n objects 辅助函数之上。
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();
}
}
有了合适的 equals()
,您现在可以:
lp.add(new Pair("1", "2"));
assert lp.contains(new Pair("1","2"));
回应下面的评论,也许最好包括一个很好的引用“为什么我需要实现hashCode()
?”
JavaPractices.com — Implementing
equals()
— “如果您重写 equals,则必须重写 hashCode”Object.equals()
contract as defined in the API documentation
关于java - 包含对列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4952631/