java HashMap应该是未排序的,但仍然根据键进行排序
根据这些:
- http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
- Difference between HashMap, LinkedHashMap and TreeMap
- java beginner : How key gets sorted in hashmaps?
Java
中的HashMap
应该是未排序的,但它是根据Key
排序的
我觉得这是个问题,因为我需要插入订单数据。所以,我用了LinkedHashMap
。但我仍然不明白为什么HashMap
会对它进行排序
有人能解释一下吗
我做了一个简单的例子来查看排序
public static void main(String[] args) {
HashMap<Integer, String> newHashMap = new HashMap<Integer, String>();
newHashMap.put(2, "First");
newHashMap.put(0, "Second");
newHashMap.put(3, "Third");
newHashMap.put(1, "Fourth");
Iterator<Entry<Integer, String>> iterator = newHashMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println("Key: " + entry.getKey());
System.out.println("Value: " + entry.getValue());
iterator.remove();
}
}
结果:
Key: 0
Value: Second
Key: 1
Value: Fourth
Key: 2
Value: First
Key: 3
Value: Third
编辑:
我尝试使用Java
中的Random
插入50个随机数,发现一些数据未排序。但是,它仍然能够对大多数整数进行排序
随机结果:
...
Key: 36
Value: random
Key: 43
Value: random
Key: 47
Value: random
Key: 44
Value: random
Key: 45
Value: random
...
# 1 楼答案
你不能假设它会被分类。在这个简单的例子中,它看起来是排序的原因是:HashMap是从“bin”内部构造的。这些箱子包含实际的元素。它们基本上是驻留在一个数组中的小列表
当一个项目被插入到HashMap中时,为了简化它,可以通过使用对象的
hashCode()
作为数组索引来找到应该插入它的“Bin”。例如,如果hashCode是2,它将被插入到Bin 2中。当这个“索引”大于数组大小时,它将被放入Bin(索引%arraySize)——也就是说,如果hashCode为5,它将被插入Bin 1由于HashMap最初的内部数组大小为10,因此在0和9之间插入
Integer
对象会同时将元素按正确的顺序放入数组中。(当然,整数的哈希码只是它的值)(注意:实际的算法和散列函数可能稍微复杂一些,但这是基本思想)
# 2 楼答案
不能对HashMap对象的顺序进行假设。他们将根据自己的意愿进行订购,具体实施情况已确定。您应该将它们视为无序的数据结构