简体   繁体   English

Java中将元素放入HashMap

[英]Put elements into HashMap in Java

Why does HashMap returning values out of order?为什么HashMap乱序返回值?

public class Main {
    public static void main(String[] args) {
        Map<Integer, String> hashMap = new HashMap<>();
        hashMap.put(40, "40");
        hashMap.put(10, "10");
        hashMap.put(30, "30");
        hashMap.put(20, "20");

        System.out.println(hashMap);
    }
}

Output:输出:

{20=20, 40=40, 10=10, 30=30} {20=20, 40=40, 10=10, 30=30}

I expected:我期望:

{40=40, 10=10, 30=30, 20=20} {40=40, 10=10, 30=30, 20=20}

A HashHap is unordered. HashHap是无序的。 So there is no particular order in which the key value pairs will be represented by toString() .因此,键值对由toString()表示没有特定的顺序。

The toString() method of HashMap , which is called by System.out.println , is implemented to represent the map as String like this: HashMaptoString()方法由System.out.println调用,实现将映射表示为字符串,如下所示:

{key0=value0, key1=value1,..., keyN=valueN}

The order can but is not guaranteed to to be the order of insertion.顺序可以但不保证是插入的顺序。

The implementation of the map interface that you are using here (HashMap) does not maintain the order of insertion.您在此处使用的映射接口 (HashMap) 的实现不维护插入顺序。 You need to use something like LinkedHashMap or TreeMap.您需要使用 LinkedHashMap 或 TreeMap 之类的东西。 Hopefully this answer will help you more Java Class that implements Map and keeps insertion order?希望这个答案能帮助你实现 Map 并保持插入顺序的更多Java 类?

您正在从哈希图中调用 toString 方法,而不是实际获取值,您应该使用 get 获取值

hashMap.get(10);

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

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