I've created a HashMap
in a 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. How can I accomplish this?
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.