6

我有两套:

 Set<Attribute> set1 = new HashSet<Attribute>(5);
 Set<Attribute> set2 = new HashSet<Attribute>(5);

 //add 5 attribute objects to each of them. (not necessarily the same objects)


 assertEquals(set1,set2); //<--- returns false, even though 
                         //the added attribute objects are equal

根据我的要求,覆盖了 Attribute 的 equals 方法:

public abstract class Attribute implements Serializable{

public int attribute;

public abstract boolean isNumerical();

@Override
public boolean equals(Object other){
    if(!(other instanceof Attribute)){
        return false;
    }

    Attribute otherAttribute = (Attribute)other;
    return (this.attribute == otherAttribute.attribute && 
            this.isNumerical() == otherAttribute.isNumerical());
}

}

调试时,甚至不调用equals方法!

有任何想法吗?

4

2 回答 2

13

您没有覆盖hashCode(),这意味着将使用默认实现。在调用之前首先HashSet检查匹配的哈希码- 这就是它如何有效地找到潜在匹配项。(很容易“存储”一个整数。)equals

基本上,您需要以hashCode与您的方法一致的方式覆盖equals

于 2012-09-04T10:27:37.183 回答
0

如果您检查调用的HashSet contains()方法调用containsKey()的源代码getEntry()。根据下面的源代码,很明显需要一个正确的hashcode()实现来调用equals。

/**
 * Returns the entry associated with the specified key in the
 * HashMap.  Returns null if the HashMap contains no mapping
 * for the key.
 */
final Entry<K,V> getEntry(Object key) {
    int hash = (key == null) ? 0 : hash(key.hashCode());
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash &&
            ((k = e.key) == key || (key != null && key.equals(k))))
            return e;
    }
    return null;
}

PS:Contains()方法是从equals of使用的AbstractCollection

于 2012-09-04T10:59:39.390 回答