【问题标题】:How do addAll in TreeSet and HashSet really work?TreeSet 和 HashSet 中的 addAll 是如何工作的?
【发布时间】:2012-05-09 23:35:29
【问题描述】:

当我在 treeSet 上添加数据时,我几乎丢失了所有数据。看来我只有第一个元素。

我阅读了这个问题Hashset vs Treeset 进行代码优化,并尝试做类似的事情。但我并没有真正成功。

输入:

int iValue = 0;

    HashSet<TagResult> results = new HashSet<TagResult>();
    for(Document doc : docs) {
        NodeList nList = doc.getElementsByTagName("TEXT");

        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                iValue = searchWords.searchOnTag(eElement, szSearch);
                if(iValue > 0) {
                    results.add(new TagResult(eElement, iValue));
                }
            }
        }
    }
    System.out.println("Set :\n-------------------------");
    for(TagResult result : results) {
        System.out.println(getTagValue("Tag",result.getElement()));
    }
    Set<TagResult> sortedResult = new TreeSet<TagResult>(new Comparator<TagResult>() {

        public int compare(TagResult e1, TagResult e2) {
            return e2.getValue() - e1.getValue();
        }
    });

    sortedResult.addAll(results);

    System.out.println("Sorted Result :\n-------------------------");
    for(TagResult result : sortedResult) {
        System.out.println(getTagValue("Tag",result.getElement()));
}

执行结果告诉我:

输出

设置:

TXT_KEY_RELIGION_POSITIF_MEDIAN_05
TXT_KEY_RELIGION_POSITIF_MEDIAN_02
TXT_KEY_RELIGION_POSITIF_04
TXT_KEY_RELIGION_POSITIF_06
TXT_KEY_RELIGION_POSITIF_05
TXT_KEY_RELIGION_POSITIF_03
TXT_KEY_RELIGION_POSITIF_MEDIAN_06
TXT_KEY_RELIGION_POSITIF_MEDIAN_01
TXT_KEY_RELIGION_POSITIF_MEDIAN_04
TXT_KEY_RELIGION_POSITIF_MEDIAN_08
TXT_KEY_RELIGION_POSITIF_MEDIAN_03
TXT_KEY_RELIGION_POSITIF_02
TXT_KEY_RELIGION_POSITIF_07
TXT_KEY_RELIGION_POSITIF_01
TXT_KEY_RELIGION_POSITIF_MEDIAN_09
TXT_KEY_RELIGION_POSITIF_MEDIAN_07

排序结果:

TXT_KEY_RELIGION_POSITIF_MEDIAN_05

我不明白我为什么会遇到这个问题。

【问题讨论】:

    标签: java hashset treeset


    【解决方案1】:

    我想是的

    e2.getValue() - e1.getValue();
    

    为您的集合中的所有项目返回 0,然后将其视为相等。尝试为您的标签打印tag.getValue() 以检查是否是这种情况。

    摘自TreeSet javadoc(强调我的):

    请注意,如果要正确实现 Set 接口,集合维护的顺序(无论是否提供显式比较器)必须与 equals 一致。 (参见 Comparable 或 Comparator 以获得与 equals 一致的精确定义。)这是因为 Set 接口是根据 equals 操作定义的,但是 TreeSet 实例使用其 compareTo 执行所有元素比较 (或 compare) 方法,因此 从集合的角度来看,此方法认为相等的两个元素相等。一个集合的行为是明确定义的,即使它的顺序与equals不一致;它只是不遵守 Set 接口的一般约定。

    【讨论】:

      猜你喜欢
      • 2015-12-29
      • 2017-04-16
      • 2013-06-16
      • 2020-10-10
      • 2023-03-25
      • 2015-06-10
      • 2012-08-18
      • 1970-01-01
      • 2012-02-25
      相关资源
      最近更新 更多