![](/img/trans.png)
[英]Will hashmap.keyset() return keys in the order they were added to the hashmap?
[英]HashMap.KeySet() returns keys in different order in Java 7 Java 8
public class TestClass {
public static void main(String[] args)
{
HashMap<String,Integer> testMap = new HashMap<String,Integer>();
testMap.put("Key1", 1);
testMap.put("Key2", 2);
testMap.put("Key3", 3);
testMap.put("Key4", 4);
testMap.put("Key5", 5);
//[Key2, Key1, Key4, Key3, Key5] //java7
//[Key2, Key1, Key5, Key4, Key3] //java8
System.out.println(testMap.keySet().toString());
}
}
為什么鍵的順序不同?
為什么鍵的順序不同?
因為:
Java規范(即javadocs)未指定HashMap的鍵集的順序,並且
Java 7和Java 8之間對HashMap的實現進行了重大更改。
這些實現更改(極大地提高了性能)導致鍵集的更改順序。
但這不被認為是“重大的”更改,因為鍵集順序始終被清楚地標記為未指定 ....意味着您不應依賴它。
不能保證按規格訂購。 各個VM可以自由實施他們選擇的任何內容。
Hashmap不會保持順序,如果要順序插入,則可以使用linkedhashmap :)
基於哈希表的Map接口的實現。 此實現提供所有可選的映射操作,並允許空值和空鍵。 (HashMap類與Hashtable大致等效,不同之處在於它是不同步的,並且允許為null。)該類不保證映射的順序。 特別是,它不能保證順序會隨着時間的推移保持恆定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.