具有两个 equals 对象的 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您还需要确保实现 hashCode(),并且当两个 Triples 相等时,它们的 hashCode 也必须相等。如果你不这样做,你会得到奇怪的行为。
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.
您没有正确覆盖类中的 equals 和 hashCode 。以下是如何编写和测试它:
http://java.sun.com/开发人员/Books/ effectivejava/Chapter3.pdf
You didn't override equals and hashCode in your class properly. Here's how to write it and test it :
http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf
看起来它只对字符串返回 true...我尝试运行下面的代码,
输出如下:
dont have C2 obj
有 k2 obj
当我将 k2 更改为 Final String k2 = "Test"; 时,输出
没有 C2 obj
没有 k2 对象
Looks like it returns true for Strings only...i tries to run the below code
the output is as below:
dont have C2 obj
has k2 obj
when i change k2 to final String k2 = "Test";, the output is
dont have C2 obj
dont have k2 obj
我无法理解你的问题,但 hashCode() 和 equals() 语义仅当你计划使用对象作为键时才重要。而且你不能让两个对象在 Map 中计算相同的哈希值......一个将覆盖另一个
I am having trouble understanding your question but hashCode() and equals() sematics are important only when you are planning to use an object as the key. And you cant have two objects evaluating to same hash in a Map...one will override the other