Java中的java.util.Iterator
和java.util.Enumeration
均可用来遍历Java中的集合框架(list,map,set等)。
但是两者也有一些区别,主要表现为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
import java.util.*; public class HashTableAndHashMap { public static void main(String[] args) { Hashtable<String,String> ht = new Hashtable<String,String>(); Map<String,String> hm = new HashMap<String,String>(); for(int i=0;i<5;i++) { ht.put(Integer.toString(i), Integer.toString(i)); hm.put(Integer.toString(i), Integer.toString(i)); } Iterator<Map.Entry<String, String>> it = hm.entrySet().iterator(); System.out.println("traverse hashmap"); while (it.hasNext()) { String key = it.next().getKey(); String value = hm.get(key); if (key.equals("2")) { it.remove(); System.out.println(key+" is removed"); continue; } System.out.println(key+":"+value); } System.out.println("hashmap final size:"+hm.size()+"\n"); System.out.println("traverse hashtable"); Enumeration<String> em = ht.keys(); while(em.hasMoreElements()) { String key = em.nextElement(); String value = ht.get(key); if (key.equals("2")) { System.out.println(key+" is removed"); continue; } System.out.println(key+":"+value); } } }
|
从上面的代码可以看到,两者遍历的方法名不同:
Iterator |
hasNext() |
next() |
Enumeration |
hasMoreElements() |
nextElement() |
而且虽然em遍历的时候不可以通过自己删除某个元素,但是可以通过collection自身删除,见上面的ht.remove()
,而通过Iterator遍历的时候不可以通过collection自身删除,如上面假如用了hm.remove()
会抛出ConcurrentModificationException
。