問題描述
根據(jù)這些:
- http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
- HashMap、LinkedHashMap和TreeMap的區(qū)別李>
- java初學(xué)者:如何在hashmaps中對(duì)key進(jìn)行排序?
Java
中的 HashMap
應(yīng)該是未排序的,但它正在根據(jù) Key
進(jìn)行排序.
The HashMap
in Java
should be unsorted but it is being sorted with respect to Key
.
我遇到了這個(gè)問題,因?yàn)槲倚枰迦胗唵螖?shù)據(jù).所以,我使用 LinkedHashMap
代替.但是我仍然很困惑為什么 HashMap
對(duì)其進(jìn)行排序.
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.
誰能解釋一下?
我做了一個(gè)簡(jiǎn)單的例子來查看排序.
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();
}
}
結(jié)果:
Key: 0
Value: Second
Key: 1
Value: Fourth
Key: 2
Value: First
Key: 3
Value: Third
我嘗試使用 Java
的 Random
插入 50 個(gè)隨機(jī)數(shù),但發(fā)現(xiàn)一些數(shù)據(jù)未排序.但是,它仍然能夠?qū)Υ蠖鄶?shù)整數(shù)進(jìn)行排序.
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.
隨機(jī)結(jié)果:
...
Key: 36
Value: random
Key: 43
Value: random
Key: 47
Value: random
Key: 44
Value: random
Key: 45
Value: random
...
推薦答案
這是巧合(不是真的,而是與哈希算法有關(guān)).
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
這個(gè)類不保證地圖的順序;特別是,它不保證訂單會(huì)隨著時(shí)間的推移保持不變.
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.
這篇關(guān)于HashMap 應(yīng)該是未排序的,但仍然根據(jù) key 排序的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!