HashMaps はこれら 2 つの方法で繰り返されるはずですか、それとも列挙は間違っていると見なされますか? 2 つのイテレータ関数を持つ単純なイテレータ プログラムを作成しました。
import java.util.*;
public class HashMapIterators
{
public static void main(String[] args)
{
HashMap<String, Integer> hMap = new HashMap<String, Integer>();
hMap.put("abc", 10);
hMap.put("pqr", 20);
hMap.put("asd", 30);
hMap.put("xyz", 40);
iteratorEnumeration(hMap);
iteratorEntrySet(hMap);
}
public static void iteratorEnumeration(HashMap hMap)
{
System.out.println("iteratorEnumeration");
Iterator it = hMap.keySet().iterator();
Enumeration em = hMap.elements(); // doesn't work
Enumeration em = new IteratorEnumeration(it); // doesn't work
// while(em.hasMoreElements())
{
}
}
public static void iteratorEntrySet(HashMap hMap)
{
System.out.println("iteratorEntrySet");
Iterator it = hMap.entrySet().iterator();
while(it.hasNext())
{
Map.Entry me = (Map.Entry)it.next();
System.out.println("Key: [" + me.getKey() + "], Value: [" + me.getValue() + "]");
}
}
}
iteratorEnumeration 関数は機能しません。これらのメソッド (elements() など) は HashTable にのみ適用できると思います。私が間違っている場合は修正してください。どの機能をいつ使用するのが適切かわかりません。したがって、私の主な質問は、entrySet メソッドに反復子を設定して HashMap を反復処理する必要があるか (私の iteratorEntrySet 関数を参照してください)、これが唯一の正しい方法ですか?