Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
367 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...