java - 具有两个相等对象的 HashSet?

标签 java hashset

我创建了一个对象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/

相关文章:

java - 有没有办法生成 JavaFX getter/setter

java - 将 long[] 更改为 Set。错误消息 : The method addAll in the type Collections is not applicable for the arguments (Set<Long>, 长[])

java - HashSet.contains 返回 false 而它不应该返回

java - HashSet 编译错误

java - 如何使类在 Java 中的不同 HashMap 中可用

java - CellList 保持选定的单元格被选中?

java - 使用已在构造函数中初始化的类的属性

java - ImageJ 叠加堆栈

Java 如何编写一个通用Util来打印所有函数当前执行的函数名称?

java - 从另一个类创建一个类的新实例