Java Enumeration介面詳解
二話不說,來看官方文件:
public interface Enumeration<E>
An object that implements the Enumeration interface generates a series of elements, one at a time.
Successive calls to the nextElement method return successive elements of the series.
實現了列舉介面的物件會生成一系列元素,一次一個。通過連續的呼叫nextElement方法獲得連續的元素。
拿vector的elements方法原始碼舉例:
public Enumeration<E> elements() {
//通過匿名類方式實現了Enumeration介面
return new Enumeration<E>() {
int count = 0;
public boolean hasMoreElements() {
return count < elementCount;
}
public E nextElement() {
synchronized (Vector.this) {
if (count < elementCount) {
return elementData(count++);
}
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
For example, to print all elements of a Vector<E> v:
for (Enumeration<E> e = v.elements(); e.hasMoreElements();)
System.out.println(e.nextElement());
Methods are provided to enumerate through the elements of a vector, the keys of a hashtable, and the values in a hashtable.
Enumerations are also used to specify the input streams to a SequenceInputStream.
NOTE: The functionality of this interface is duplicated by the Iterator interface.
In addition, Iterator adds an optional remove operation, and has shorter method names.
New implementations should consider using Iterator in preference to Enumeration.
說明:本介面功能已被Iterator介面取代。Iterator介面擴充套件了刪除方法,並且具有更簡潔的方法名。
再來寫個例項,加深瞭解:
package com.dylan.collection;
import java.util.Enumeration;
import java.util.Vector;
/**
* 測試列舉介面,
* 可用於遍歷集合型別,目前已被迭代器Iterator取代
*
* @author xusucheng
* @create 2017-12-25
**/
public class EnumerationTest {
public static void main(String[] args) {
Vector v = new Vector();
v.add("Jack");
v.add("ate");
v.add("lots of oranges.");
Enumeration<String> e = v.elements();
String output = "";
while (e.hasMoreElements()) {
output += e.nextElement() + " ";
}
System.out.println(output);
}
}
相關文章
- Java中的Enumeration、Iterable和Iterator介面詳解Java
- Java中「Future」介面詳解Java
- 詳解Java函式式介面Java函式
- Java 本地介面 JNI 使用詳解Java
- Java介面回撥機制詳解Java
- JAVA集合詳解(Collection和Map介面)Java
- (轉)簡單介紹java EnumerationJava
- Java Comparable 和 Comparator 介面詳解Java
- Java中的介面與抽象類詳解Java抽象
- Iterator及Enumeration
- 類與介面(二)java的四種內部類詳解Java
- 介面測試--apipost介面斷言詳解API
- 「MoreThanJava」Day 7:介面詳解Java
- 抽象類及介面詳解抽象
- C#-介面(Interface)詳解C#
- 介面和抽象類詳解抽象
- Java註解詳解Java
- Java 註解詳解Java
- 圖解Dubbo,Dubbo服務介面詳解圖解
- Go 語言介面詳解(一)Go
- Go 語言介面詳解(二)Go
- PHP遍歷介面Iterator詳解PHP
- rails的介面查詢詳解AI
- java反射詳解Java反射
- Java Stream 詳解Java
- Java 反射詳解Java反射
- 【Java】JDBC詳解JavaJDBC
- Java SPI詳解Java
- 詳解 Java NIOJava
- Java鎖詳解Java
- java CountDownLatch 詳解JavaCountDownLatch
- Java RMI詳解Java
- JAVA ANNOTATION詳解Java
- Java容器詳解Java
- java方法詳解Java
- Java註解(Annotation)詳解Java
- springboot介面接參註解詳解Spring Boot
- Java註解最全詳解(超級詳細)Java