Dictionary element Traversal

Source: Internet
Author: User
When I interviewed other people in the past, I often asked candidates how to traverse the elements in Hashtable in C # and get the Key and Value for each time.

This problem has been frequently asked. Including the traversal of Map elements in Java. I have answered this question in the Java edition of shuimu Tsinghua.

. NET platform:

IDictionary dictionary = new Hashtable ();
Foreach (DictionaryEntry entry in dictionary)
{
Object key = entry. Key;
Object val = entry. Value;
}

In the Java environment:

Map map = new HashMap ();
Iterator iter = map. entrySet (). iterator ();
While (iter. hasNext ()){
Map. Entry entry = (Map. Entry) iter. next ();
Object key = entry. getKey ();
Object val = entry. getValue ();
}

Comments:
The foreach method is introduced in the. NET environment, but the types returned by the GetEnumerator () method of IDictionary and ICollection are different. This is easy to confuse. Many beginners may write errors. The following are common examples for beginners:

IDictionary dictionary = new Hashtable ();
Foreach (Object val in dictionary)
{
//
}

This is a mine ,. NET's basic class library and C #, with the interaction of language design (the way foreach is supported), produced this mine, which may also be called a defect ......

In Java, it is a little troublesome to use it. Many beginners do not use proper methods to traverse Map. Even some Java programmers who have been writing for many years are using stupid methods.

Map map = new HashMap ();
Iterator iter = map. keySet (). iterator ();
While (iter. hasNext ()){
Object key = iter. next ();
Object val = map. get (key );
}

This method is less efficient.

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.