Iterating HashMap on order it has been set

爷,独闯天下 提交于 2020-01-14 06:59:11

问题


I've set a HashMap on certain order but it is iterated on a strange order!

Please consider code below:

HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", "1");
map.put("Name", "the name");
map.put("Sort", "the sort");
map.put("Type", "the type");

...

for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
}

and the result:

Name: the name
Sort: the sort
Type: the type
ID: 1

I need to iterate it in order i've put the entries. Any help will be appreciated.


回答1:


The order depends on the result of the hashCode() function in the keys you are inserting which, unless you did something strange, is going to be mostly random (but consistent). What you are looking for is a sorted map such as a LinkedHashMap

Check out a little bit about how hashtables work here if you are interested in the details.




回答2:


That's how HashMap works internally. Replace HashMap with LinkedHashMap which additionally remembers the order of insertion:

Map<String, String> map = new LinkedHashMap<String, String>();


来源:https://stackoverflow.com/questions/13893794/iterating-hashmap-on-order-it-has-been-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!