Enumeration(枚舉)接口的作用和Iterator類似,只提供了遍歷Vector和HashTable類型集合元素的功能,不支持元素的移除操作。
Java8中Enumeration接口的源碼:
public interface Enumeration<E> {通過Enumeration的源碼分析可得,Enumeration有兩個方法:
/**
* Tests if this enumeration contains more elements.
*
* @return <code>true</code> if and only if this enumeration object
* contains at least one more element to provide;
* <code>false</code> otherwise.
*/
boolean hasMoreElements();//判斷是否包含元素
/**
* Returns the next element of this enumeration if this enumeration
* object has at least one more element to provide.
*
* @return the next element of this enumeration.
* @exception NoSuchElementException if no more elements exist.
*/
E nextElement();//獲得下一個元素
}
(1)boolean hasMoreElements();//是否還有元素,如果有返回true,否則表示至少含有一個元素
(2)E nextElement();//如果Enumeration枚舉對象還有元素,返回對象只能的下一個元素,否則拋出NoSuchElementException異常。
簡單示例:
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();//返回Enumeration對象
while(e.hasMoreElements()){
String value = (String)e.nextElement();//調用nextElement方法獲得元素
System.out.print(value);
}
}
}