下面的代码没有给我预期的结果:
public static void main (String[] args) {
Set<Pair> objPair = new LinkedHashSet<Pair>();
objPair.add(new Pair(1, 0));
System.out.println("Does the pair (1, 0) exists already? "+objPair.contains(new Pair(1, 0)));
}
private static class Pair {
private int source;
private int target;
public Pair(int source, int target) {
this.source = source;
this.target = target;
}
}
结果将是:
Does the pair (1, 0) exists already? false
我不明白为什么它不起作用。 或者我可能错误地使用了“包含”方法(或出于错误的原因)。
还有一个问题, 如果我两次添加相同的值,它会被接受,即使是一个集合
objPair.add(new Pair(1, 0));
objPair.add(new Pair(1, 0));
它不会接受/识别我创建的类对吗?
提前致谢。
最佳答案
您需要覆盖Pair
类中的hashCode
和equals
方法。 LinkedHashSet
(以及其他使用哈希码的 Java 对象)将使用它们来定位和查找您的 Pair
对象。
关于java - "contains"哈希集方法问题 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21103000/