如何使 java HashSet / HashMap 与任何对象一起工作?
是否可以使 HashSet 与任何对象一起工作?我试图让对象实现 可以比较,但没有帮助
import java.util.HashSet;
public class TestHashSet {
public static void main(String[] args) {
class Triple {
int a, b, c;
Triple(int aa, int bb, int cc) {
a = aa;
b = bb;
c = cc;
}
}
HashSet<Triple> H = new HashSet<Triple>();
H.add(new Triple(1, 2, 3));
System.out.println(H.contains(new Triple(1, 2, 3)));//Output is false
}
}
Is it possible to make HashSet work with any Object ?? I tried to make the Object implement
Comparable but it didn't help
import java.util.HashSet;
public class TestHashSet {
public static void main(String[] args) {
class Triple {
int a, b, c;
Triple(int aa, int bb, int cc) {
a = aa;
b = bb;
c = cc;
}
}
HashSet<Triple> H = new HashSet<Triple>();
H.add(new Triple(1, 2, 3));
System.out.println(H.contains(new Triple(1, 2, 3)));//Output is false
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要实施
equals(Object)
和hashCode()
对象相等时哈希码也相等:
确保当示例中的
you need to implement
equals(Object)
andhashCode()
ensure that the hashcodes are equal when the objects are equal
in your example:
为了使其正常工作,您需要实现 equals() 和 hashcode(),并且还需要确保它们正确实现,遵循 Javadoc 中规定的合同(完全有可能实现它们而不遵循这份合同,但你会得到奇怪的结果,并且可能很难追踪错误!)
请参阅此处< /a> 对于一个描述。
For it to work properly you'll need to implement equals() and hashcode() and you'll also need to make sure they're implemented properly, following the contract set out in the Javadoc (it's perfectly possible to implement them not following this contract but you'll get bizarre results with potentially hard to track down bugs!)
See here for a description.
它已经适用于任何对象。我建议您需要阅读 Javadoc 而不是猜测需求。
It already does work with any object. I suggest you need to read the Javadoc instead of guessing about the requirements.