简体   繁体   中英

Put elements into HashMap in Java

Why does HashMap returning values out of order?

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}

I expected:

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

A HashHap is unordered. So there is no particular order in which the key value pairs will be represented by toString() .

The toString() method of HashMap , which is called by System.out.println , is implemented to represent the map as String like this:

{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. You need to use something like LinkedHashMap or TreeMap. Hopefully this answer will help you more Java Class that implements Map and keeps insertion order?

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

hashMap.get(10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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