我创建了一个对象HashSet,值是一个对象(Triple),它是我自己的类。但是我有一件奇怪的事情,当我的 HashSet 上有两个相等的对象时,这可能吗?这是我在 Triple 类中重写 equals 的方法
@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(),并且当两个三元组相等时,它们的 hashCode 也必须相等。如果你不这样做,你会得到奇怪的行为。
关于java - 具有两个相等对象的 HashSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4055780/