我需要澄清一下 java 认为什么是重复的。
考虑以下代码:
public class Fruit {
private String name;
private int juice;
public Fruit(String name, int j) {
this.name=name;
this.juice=j;
}
//some more code here
public String toString() {
return this.name;
}
public boolean equals(Object fruit) {
return (((Fruit)fruit).name.equals(this.name));
}
}
public class Test {
public static void main(String[] args) {
Fruit a=new Fruit("Apple", 25);
Fruit b=new Fruit("Apple", 22);
HashSet<Fruit> hs=new HashSet<Fruit>();
hs.add(a);
hs.add(b);
System.out.println(a.equals(b));
System.out.println(hs.size());
}
}
我创建了一个 Fruit 类,我在其中覆盖了 equals(),这样如果两个对象的名称相等,它们就被认为是相等的。 然后,我将两个 Fruit 对象(具有相同的名称)添加到一个 HashSet。
现在,HashSet 应该可以防止尝试添加两个相等的对象。 虽然,上面代码的输出是:
是的 2
因此,一方面,Java 将这两个对象(a 和 b)视为相等,另一方面 - HashSet 并不将这两个对象视为相等。 那么我在这里缺少什么?
提前致谢!
最佳答案
HashSet doesn't consider these two as equals. So what am I missing here?
您错过了在 Fruit
类中覆盖 hashCode
。
@Override
public int hashCode(){
return 31 * this.name.hashCode();
}
关于java - 需要澄清 Java 中的 HashSet 和重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20405284/