gpt4 book ai didi

java assertEquals 集合

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:11 26 4
gpt4 key购买 nike

我有两套:

 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 方法甚至都没有被调用!

有什么想法吗?

最佳答案

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

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

关于java assertEquals 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12261513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com