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.