简体   繁体   English

遍历哈希图

[英]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 结果:3,2,1,4

Why is the order all mixed :S ? 为什么所有命令都混合了:S?

Why is the order all mixed :S ? 为什么所有命令都混合了:S?

Because a HashMap doesn't guarantee any order of iteration of it's element. 因为HashMap不能保证其元素的任何迭代顺序。 You will not get any constant order. 您将不会得到任何恒定的顺序。 If you want the insertion order, use a LinkedHashMap . 如果需要插入顺序,请使用LinkedHashMap

If you have a look at the docs :- 如果您看一下文档

Hash table based implementation of the Map interface. 基于哈希表的Map接口的实现。 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; (HashMap类与Hashtable大致等效,不同之处在于它是不同步的,并且允许为null。)该类不保证映射的顺序。 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. 按照@Rohit的建议,如果要维护顺序,请尝试使用LinkedHashMap

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

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