一直以来,也经常有人问这个问题。包括Java下Map的元素的遍历。我在水木清华的Java版也回答过这个问题。
.NET平台下:
IDictionary dictionary = new Hashtable();
foreach (DictionaryEntry entry in dictionary)
{
Object key = entry.Key;
Object val = entry.Value;
}
foreach (DictionaryEntry entry in dictionary)
{
Object key = entry.Key;
Object val = entry.Value;
}
Java环境下:
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();
}
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}
点评:
.NET环境下,引入了foreach的写法,但是IDictionary和ICollection的GetEnumerator()方法返回的类型是不一样的,这一点,很容易让人迷惑,初学者很多都会写错。如下是初学者常用的写法:
IDictionary dictionary = new Hashtable();
foreach (Object val in dictionary)
{
//
}
foreach (Object val in dictionary)
{
//
}
Java下,使用起来的方式,有点麻烦,很多初学者,不使用恰当的方法遍历Map,甚至一些写了多年Java程序员都是用比较笨的办法。
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}