简体   繁体   English

HashMap.KeySet()在Java 7中以不同顺序返回键Java 8

[英]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());
    }

}

Why there is difference in the order of the keys? 为什么键的顺序不同?

why there is difference in the order of the keys ? 为什么键的顺序不同?

Because: 因为:

  1. the Java specs (ie the javadocs) do not specify the order of a HashMap's keyset, and Java规范(即javadocs)未指定HashMap的键集的顺序,并且

  2. there were major changes to the implementation of HashMap between Java 7 and Java 8. Java 7和Java 8之间对HashMap的实现进行了重大更改。

Those implementation changes (which gave significant performance improvements) resulted in the order of the keyset changing. 这些实现更改(极大地提高了性能)导致键集的更改顺序。

But that is not considered a "breaking" change because the keyset order has always been clearly noted as unspecified .... meaning that you should not rely on it. 但这不被认为是“重大的”更改,因为键集顺序始终被清楚地标记为未指定 ....意味着您不应依赖它。

Ordering is not guaranteed as per spec. 不能保证按规格订购。 Individual VM's are free to implement whatever they choose. 各个VM可以自由实施他们选择的任何内容。

Hashmap不会保持顺序,如果要顺序插入,则可以使用linkedhashmap :)

Hash table based implementation of the Map interface. 基于哈希表的Map接口的实现。 This implementation provides all of the optional map operations, and permits null values and the null key. 此实现提供所有可选的映射操作,并允许空值和空键。 (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; (HashMap类与Hashtable大致等效,不同之处在于它是不同步的,并且允许为null。)该类不保证映射的顺序。 in particular, it does not guarantee that the order will remain constant over time. 特别是,它不能保证顺序会随着时间的推移保持恒定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM