Enumeration 接口(枚舉)
java.util.Enumeration 接口的作用與 Iterator 接口類似,但只提供了遍歷 Vector 和 Hashtable (及子類 Perperties )類型集合元素的功能,不支持元素的移除操作。此外, Iterator 接口添加了一個可選的移除操作,並使用較短的方法名。
注:此接口的功能與 Iterator 接口的功能是重複的。新的實現應該優先考慮使用 Iterator 接口而不是 Enumeration 接口。
public Enumeration elements(); // 從索引 0 開始列舉向量中所有元素。該方法返回一個列舉( Enumeration )對象。
通常用 Enumeration 中的以下兩個方法打印向量中的所有元素:
(1) boolean hasMoreElements(); // 是否還有元素,如果返回 true ,則表示至少含有一個元素
(2) public Object nextElement(); // 如果 Enumeration 枚舉對象還含有元素,該方法返回對象中的下一個元素。如果沒有,則拋出 NoSuchElementException 異常。
用法一:
// vec 是接口實現類 Vector( 集合 ) 的對象, vec.elements() 獲得 Vector( 集合 ) 的一個元素。
for(Enumeration e = vec.elements(); e.hasMoreElements();)
{ System.out.println(e.nextElement()); }
用法二:
//e is an object that implements the Enumeration interface
while (e.hasMoreElements()) {
Object o= e.nextElement();
System.out.println(o);
}
這樣,實現 Enumeration 接口的對象,它生成一系列元素,一次生成一個。即實現該接口的對象由一系列的元素組成,可以連續地調用 nextElement() 方法來得到 Enumeration 枚舉對象中的元素。
例如: TestEnumeration.java
import java.util.*;
public class TestEnumeration{
public static void main(String[] args){
Vector v = new Vector();
v.addElement("Lisa");
v.addElement("Billy");
v.addElement("Mr Brown");
Enumeration e = v.elements();
while(e.hasMoreElements()){
String value = (String)e.nextElement();
System.out.print(value);
}
}
}
輸出結果:
LisaBillyMr Brown