Java Enumeration介面詳解

indexman發表於2017-12-25

二話不說,來看官方文件:

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);
    }
}
















相關文章