gpt4 book ai didi

java - TreeSet 和 HashSet 中的 addAll 究竟是如何工作的?

转载 作者:搜寻专家 更新时间:2023-10-31 19:29:36 25 4
gpt4 key购买 nike

当我在 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

我不明白为什么我有这个问题。

最佳答案

我认为

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

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

摘自 TreeSet javadoc (强调我的):

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

关于java - TreeSet 和 HashSet 中的 addAll 究竟是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10380808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com