【发布时间】:2014-02-01 21:21:48
【问题描述】:
以下代码没有给我预期的结果:
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?
提前致谢。
【问题讨论】:
-
HashSet使用哈希码。你的hashCode()实现在哪里? -
哦,是的,我是这方面的新手,我可能需要进一步研究它:) 非常感谢!