带有“包含”的问题哈希集方法(Java) [英] Issue with "contains" hashset method (Java)
问题描述
以下代码没有给我期望的结果:
The following code is not giving me the result I'm expecting:
public static void main (String[] args) {
Set<Pair> objPair = new LinkedHashSet<Pair>();
objPair.add(new Pair(1, 0));
System.out.println("Does the pair (1, 0) exists already? "+objPair.contains(new Pair(1, 0)));
}
private static class Pair {
private int source;
private int target;
public Pair(int source, int target) {
this.source = source;
this.target = target;
}
}
结果将是:
Does the pair (1, 0) exists already? false
我不明白为什么它不起作用。
还是我使用的 contains方法错误(或由于错误的原因)。
I can't understand why it's not working. Or maybe I'm using the "contains" method wrong (or for the wrong reasons).
还有另一个问题,如果我两次添加相同的值,即使是集合,它也会被接受
There is also another issue, if I add the same value twice, it will be accepted, even being a set
objPair.add(new Pair(1, 0));
objPair.add(new Pair(1, 0));
它不接受/识别我创建的Pair对吗?
It won't accept/recognize the class Pair I've created?
谢谢。
推荐答案
如果没有您自己的hashCode()实现,则 Java仅当两个 Pair
对象完全相同时才认为它们相等和 new
创建一个新对象。在您的情况下,如果 Pair
对象的 source
和<$ c具有相同的值,则它们应被视为相等。 $ c> target -为此,您需要告诉Java如何测试 Pair
对象是否相等。 (并且要使哈希图按您期望的方式工作,还需要生成与与equals 一致的哈希码-粗略地说,这意味着等于对象必须生成相同的hashCode,并且不相等的对象应生成不同的哈希码。
Without your own hashCode() implementation, Java considers two Pair
objects equal only if they are the exact same object and new
, by definition, always creates a 'new' object. In your case, you want Pair
objects to be consider equal if they have the same values for source
and target
-- to do this, you need to tell Java how it should test Pair
objects for equality. (and to make hash maps work the way you expect, you also need to generate a hash code that is consistent with equals -- loosely speaking, that means equal objects must generate the same hashCode, and unequal objects should generate different hash codes.
大多数IDE会为您生成不错的hashcode()和equals()方法我的生成的是:
Most IDEs will generate decent hashcode() and equals() methods for you. Mine generated this:
@Override
public int hashCode() {
int hash = 3;
hash = 47 * hash + this.source;
hash = 47 * hash + this.target;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Pair other = (Pair) obj;
if (this.source != other.source) {
return false;
}
if (this.target != other.target) {
return false;
}
return true;
}
这篇关于带有“包含”的问题哈希集方法(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!