The order of elements traversal in Java about HashMap

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.