問題描述
根據這些:
- http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
- HashMap、LinkedHashMap和TreeMap的區別李>
- java初學者:如何在hashmaps中對key進行排序?
Java
中的 HashMap
應該是未排序的,但它正在根據 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();
}
}
結果:
Key: 0
Value: Second
Key: 1
Value: Fourth
Key: 2
Value: First
Key: 3
Value: Third
我嘗試使用 Java
的 Random
插入 50 個隨機數,但發現一些數據未排序.但是,它仍然能夠對大多數整數進行排序.
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");
最后一次.
輸出將是
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 應該是未排序的,但仍然根據 key 排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!