【发布时间】:2013-12-22 16:55:56
【问题描述】:
我需要澄清一下 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的含义。为什么它有“哈希”部分:) -
谢谢大家的回答。我将覆盖 HashCode()。还有一个问题:如果我将使用其他不允许重复且不使用哈希的数据结构,例如 TreeSet,该怎么办?
-
如果你使用
TreeSet,你要么必须传递知道如何比较水果的Comparator对象,要么让Fruit实现Comparable,所以它也需要额外的工作。 -
我不知道标准 JDK 中的任何
Set实现仅使用equals方法。
标签: java duplicates hashset