gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:33:33 25 4
gpt4 key购买 nike

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 ?

因为:

  1. Java 规范(即 javadoc)没有指定 HashMap 的键集顺序,并且

  2. Java 7 和 Java 8 之间 HashMap 的实现发生了重大变化。

这些实现更改(显着提高了性能)导致键集的顺序发生变化。

但这并不被视为“重大”更改,因为键集顺序始终被明确标记为未指定 ....这意味着您不应该依赖它。

关于java - HashMap.KeySet() 在 Java 7 Java 8 中以不同顺序返回键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38587711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com