简体   繁体   中英

Iterate through hashmap

Something very wiered.

This is my code:

Map<String, Object[]> data = new HashMap<String, Object[]>();
    data.put("1", new Object[] {"VENDOR_NAME", "COUNTRY_CODE", "PREFIX" , "RATE" , "CURRENCY" });
    data.put("2", new Object[] {10d, "John", 1500000d});
    data.put("3", new Object[] {2d, "Sam", 800000d});
    data.put("4", new Object[] {3d, "Dean", 700000d});

    Set<String> keyset = data.keySet();
    int rownum = 0;
    for (String key : keyset) {
        System.out.println(key);
    }

The result: 3 , 2 ,1 ,4

Why is the order all mixed :S ?

Why is the order all mixed :S ?

Because a HashMap doesn't guarantee any order of iteration of it's element. You will not get any constant order. If you want the insertion order, use a LinkedHashMap .

If you have a look at the docs :-

Hash table based implementation of the Map interface. 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; in particular, it does not guarantee that the order will remain constant over time.

That's why you're seeing the order getting all mixed up. As @Rohit suggested, try using a LinkedHashMap if you want to maintain the order.

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