这个问题只是出于好奇,但我注意到使用keyset迭代HashMap似乎总是按排序顺序进行。显然,HashMaps永远不会保留插入顺序,但是排序键顺序对我来说似乎有点奇怪。使用此示例:
import java.util.HashMap;
public class test {
public static void main(String[] args) {
HashMap<Integer, String> someMap = new HashMap<Integer, String>();
someMap.put(0, "nothing");
someMap.put(7, "nothing");
someMap.put(3, "nothing");
someMap.put(4, "nothing");
someMap.put(10, "nothing");
someMap.put(11, "nothing");
someMap.put(2, "nothing");
someMap.put(1, "nothing");
someMap.put(5, "nothing");
for (Integer someInt : someMap.keySet()) {
System.out.println(someInt);
}
}
}
输出:
0
1
2
3
4
5
7
10
11
这是否可靠且一致?如果 HashMap 实现是一个数组,如果键集只是迭代从 0 开始的所有可用数组索引,这将是有意义的,但我可能是错的,它比这更复杂。
不保证HashMaps
和HashSets
期间的特定顺序。您可以通过删除和添加一些元素来扰乱您的订单。
看看这个:
import java.util.HashMap;
public class test {
public static void main(String[] args) {
HashMap<Integer, String> someMap = new HashMap<Integer, String>();
someMap.put(0, "nothing");
someMap.put(7, "nothing");
someMap.put(3, "nothing");
someMap.put(4, "nothing");
someMap.put(10, "nothing");
someMap.put(11, "nothing");
someMap.put(2, "nothing");
someMap.put(10004, "nothing");
someMap.put(1, "nothing");
someMap.put(5, "nothing");
for (Integer someInt : someMap.keySet()) {
System.out.println(someInt);
}
}
}
在大多数排序的哈希集中,哈希函数排除了特定值的去向。
来自 javadoc:
此类不保证映射的顺序;特别是,它不保证顺序在一段时间内保持不变。
您所看到的可能是关于 JVM 实现以及如何管理哈希代码的巧合,或者可能(但不太可能(:
请注意,使用具有相同 hashCode(( 的许多键是降低任何哈希表性能的可靠方法。为了减轻影响,当键具有可比性时,此类可能会使用键之间的比较顺序来帮助中断关系。
无论如何,这是不可靠或恒定的。
可能是这样;但由于它没有记录在Java文档中,所以你不应该根据这种行为进行编码。由于新的 java 版本可以更改HashMap
实现,这可能会给出非升序键;因此,无论您根据此类行为所做的任何代码都会中断