【发布时间】:2014-01-30 22:17:11
【问题描述】:
以下程序打印 一个|两个 一个|两个 使用 HashSet 时。如果我将它更改为 TreeSet 它只打印 一个|两个
难道不希望用相同的数据集给出相同的结果吗?我在这里做错了什么?在 TreeSet 的情况下,程序中的什么使第二条记录重复?
导入 java.util.HashSet; 导入 java.util.Set;
public class SetTest {
public static void main(String arg[]) {
Set<Bk> bookList = new HashSet<Bk>();
//Set<Bk> bookList = new TreeSet<Bk>();
bookList.add(new Bk("one","two"));
bookList.add(new Bk("one","two"));
for(Bk book: bookList){
System.out.println(book);
}
}
}
class Bk implements Comparable<Bk> {
public String name;
public String author;
public String toString(){
return name+"|"+ author;
}
Bk(String name, String author) {
this.name = name;
this.author = author;
}
@Override
public int compareTo(Bk that) {
int author = this.author.compareTo(that.author);
int name = 0;
if (author == 0) {
name = this.name.compareTo(that.name);
return name;
} else {
return author;
}
}
}
【问题讨论】:
-
发帖前请务必阅读相关类的javadoc。
-
@SotiriosDelimanolis 我编辑了问题以格式化代码;
<Bk>在我格式化之前没有出现在Comparable上。现在compareTo方法的Bk参数是有意义的。 -
hashCode和equals不见了...... -
@rgettman 好的,谢谢!