The order of elements traversal in Java about HashMap
Today, when you traverse the elements in HashMap using the following method
1 for (entry<string, string> entry:hashMap.entrySet ()) {2 Messageformat.format ("{0}={1}", Entry.getkey (), Entry.getvalue ()); 3}
Found that the elements are not in accordance with the order of the previous join HashMap output, this problem I did not pay attention to, and later on the Internet to check the reason, found that:HashMap scattered diagram, Hashtable hash list is "in favor of random search hash (hash) order". Not by input order. The traversal can only be output in full, without order . You can even re-hash rehash () to get an internal order that is more conducive to random access.
In summary, sequential output is not required when traversing hashmap or Hashtable, that is, the order is irrelevant.
1 map<string, string> parammap = new hashmap<string, string> ();
You can use Java.util.LinkedHashMap to traverse in the order in which they were added.
1 map<string, string> parammap = new Linkedhashmap <string, string> ();
Similar to Java.util.LinkedHashSet .
The order of elements traversal in Java about HashMap