HashSet有两个等于对象? [英] HashSet with two equals object?

查看:111
本文介绍了HashSet有两个等于对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created an object HashSet, and the value is an object (Triple) which is my own class. But I get a strange thing, when there are two equal objects on my HashSet, is it possible? Here is my overriding method for the equals in the class 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也必须相等。如果你不这样做,你会得到奇怪的行为。

You need to be sure to implement hashCode() as well, and when two Triples are equal, their hashCodes must also be equal. If you don't do that, you will get strange behavior.

这篇关于HashSet有两个等于对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆