Java中Iterator和Enumeration的区别

Java中的java.util.Iteratorjava.util.Enumeration均可用来遍历Java中的集合框架(list,map,set等)。 但是两者也有一些区别,主要表现为:

  • 并非所有的collection都支持Enumeration的遍历,但是都支持Iterator的遍历。如Hashtable支持但是HashMap不支持。但是两者都支持Iterator的遍历。

  • Iterator 提供了remove()方法可以在遍历的同时删除集合中的元素,但是Enumeration没有这个方法,对集合中的元素只读

  • 两者的方法名不同,具体见下面的代码

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

/**
* compare Iterator with Enumeration
*/

import java.util.*;
public class HashTableAndHashMap
{
public static void main(String[] args)
{
//init the map
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));
}

//different ways of iterating the values
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"))
{
//em不提供remove的方法,但是可以通过ht.remove(key)删除
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