【问题标题】:Is Java TreeSet and HashSet expected to give different result with the same data?Java TreeSet 和 HashSet 是否期望用相同的数据给出不同的结果?
【发布时间】: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 我编辑了问题以格式化代码; &lt;Bk&gt; 在我格式化之前没有出现在 Comparable 上。现在compareTo 方法的Bk 参数是有意义的。
  • hashCodeequals 不见了......
  • @rgettman 好的,谢谢!

标签: java hashset treeset


【解决方案1】:

HashSet 类将使用hashCodeequals 来确定集合中是否已经存在重复项。 TreeSet 类将使用 Comparable(或 Comparator)这一事实来订购商品并确定是否存在重复。

你有BkComparable&lt;Bk&gt;,所以TreeSet 可以正常工作。但是,您仍然需要覆盖 hashCodeequals 以便 HashSet 也可以正常工作。

【讨论】:

  • 感谢您的解释...我得到了一致的结果,覆盖了 equals 和 hashCode.. 不知道 TreeSet 和 HashSet 依赖于不同的方法来检查重复...
【解决方案2】:

如果您想与 HashSet 保持一致的行为,则必须按照 Javadoc 实现 hashCode() 和 equals(),并与您的 compareTo() 方法保持一致。

【讨论】:

    猜你喜欢
    • 2018-05-05
    • 2021-12-26
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多