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());
}
}
为什么键的顺序有所不同?HashMap.KeySet()在Java 7中以不同顺序返回键Java 8
其实,集合中的元素的顺序(如keySet)是未定义的,可以是任何东西。如果您需要特定订单,请在使用SortedMap或排序键之前使用它们。 Java版本的更改可能会导致使用不同大小的数组来保存HashMap中的值(只是猜测)。 –
集合无序 – Dariusz
您运行程序和获取键集的次数大多数时间都不同。所以在java 7或java 8密钥集代码中没有区别。 – Imran