根據這些: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
...
HashMap不保證是未排序的。對於值0到11,由於HashMap的實現方式,您將按順序獲取它們。 HashMap通過hashCode將條目存儲到數組中。 Integer的hashCode與int值相同。 –
同樣的情況發生在'HashSet',它在引擎蓋下使用了'HashMap'。 –