HashSet有两个等于对象?

我创建了一个对象HashSet,该值是一个对象(Triple),这是我自己的类。 但是我得到一个奇怪的事情,当我的HashSet上有两个相同的对象时,它有可能吗? 这是我在类Triple中的等于的重写方法

@Override public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; Triple otherTriple = (Triple)other; if(otherTriple.getSubject().equals(getSubject()) && otherTriple.getPredicate().equals(getPredicate()) && otherTriple.getObject().equals(getObject())) return true; return false; 

}

你需要确保实现hashCode(),当两个三元组相等时,它们的hashCodes也必须相等。 如果你不这样做,你会得到奇怪的行为。

你没有正确地覆盖你的类中的equals和hashCode。 以下是编写和测试它的方法:

http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf

看起来它仅对Strings返回true …我试图运行下面的代码

  final HashSet carHashSet = new HashSet(); final Car c1 = new Car("black","ZX","deisel"); final Car c2 = new Car("black","ZX","deisel"); carHashSet.add(c1); if (carHashSet.contains(c2)) System.out.println("has c2 obj"); else System.out.println("dont have C2 obj"); final HashSet stringHashSet = new HashSet(); final String k1 = "test"; final String k2 = "test";//final String k2 = "Test"; stringHashSet.add(k1); if (stringHashSet.contains(k2)) System.out.println("has k2 obj"); else System.out.println("dont have k2 obj"); 

输出如下:

没有C2 obj有k2 obj

当我将k2更改为最终字符串k2 =“Test”;时,输出为

没有C2 obj没有k2 obj

我无法理解您的问题,但只有当您计划使用对象作为键时,hashCode()和equals()语义才是重要的。 你不能让两个对象在Map中评估相同的哈希值…一个会覆盖另一个