HashMap应该是未排序的,但仍然按照键排序 [英] HashMap should be unsorted but still sorts according to key
问题描述
根据这些:
- http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
- Java中的HashMap,LinkedHashMap和SortedMap之间的区别
- java初学者:如何在hashmaps中按键进行排序?
- http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
- Difference between HashMap, LinkedHashMap and SortedMap in Java
- java beginner : How key gets sorted in hashmaps?
HashMap
在 Java
应该是未排序的,但是它正在被排序关于 Key
。
The HashMap
in Java
should be unsorted but it is being sorted with respect to Key
.
我遇到这个问题,因为我需要插入订单数据。所以,我使用了 LinkedHashMap
。但是我仍然很困惑,为什么 HashMap
将它排序。
I experienced this as a problem because I needed inserted-order data. So, I used LinkedHashMap
instead. But still I am confused why the HashMap
sorted it.
有人可以解释吗?
我做了一个简单的例子来查看排序。
I did a simple example to view the sort.
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();
}
}
结果: strong>
Result:
Key: 0
Value: Second
Key: 1
Value: Fourth
Key: 2
Value: First
Key: 3
Value: Third
编辑:
我试图使用随机
Java
,我发现一些数据未排序。但是,它仍然设法排序大部分的整数。
I tried to insert 50 random numbers using Random
of Java
and I found some data unsorted. But, it still manages to sort most of the integers.
随机结果:
...
Key: 36
Value: random
Key: 43
Value: random
Key: 47
Value: random
Key: 44
Value: random
Key: 45
Value: random
...
推荐答案
这是巧合(不是真的,而是与散列算法有关)。
It's a coincidence (not really, rather it has to do with the hashing algorithm).
尝试添加
newHashMap.put(-5, "Fifth");
as last。
输出将
Key: 0
Value: Second
Key: 1
Value: Fourth
Key: 2
Value: First
Key: 3
Value: Third
Key: -5
Value: Fifth
javadoc具体说
The javadoc specifically says
关于地图顺序的保证;特别是,它不能保证订单在一段时间内保持不变。
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
这篇关于HashMap应该是未排序的,但仍然按照键排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!