我需要复制对从 HashMap 类的函数 entrySet() 返回的集合进行的排序。我不明白它是如何排序的。
以下代码:
HashMap<String, Integer> testList = new HashMap<String, Integer>();
testHash.put("B", 1);
testList.put("A", 3);
testList.put("E", 2);
testList.put("D", 5);
testList.put("C", 4);
//testList.put("B", 1);
//testList.put("C", 4);
//testList.put("A", 3);
//testList.put("E", 2);
//testList.put("D", 5);
for (Map.Entry<String, Integer> entry : testList.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
返回:
D - 5
E - 2
A - 3
B - 1
C - 4
为什么?注释掉的代码以相同的顺序返回它们。
最佳答案
I don't understand how it is sorted.
那是因为它不遵循任何特定的顺序。实际排序取决于您放入的项目的哈希码、放入它们的顺序以及哈希桶的数量(与负载因子密切相关)。
No matter in which order I put the items in the
HashMap
, it always returns them in the same order.
那是因为item个数相同,items的hash code相同,没有遇到因为hash冲突导致输出重排的顺序。
可以构建一个排序,为同一组项目生成略有不同的输出。然而,外卖教训是订单不可靠,因此您不应该期望您的元素以任何特定顺序出现。
如果您必须维护特定的顺序,Java 提供了两个不错的选择:
- 您可以使用
LinkedHashMap
根据插入顺序来预测顺序,或者 - 您可以使用
TreeMap
将您的项目按键排序。
关于java - HashMap.entryset()返回的Set,是如何排序的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29425024/