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
















posted @ 2017-12-25 15:40  一锤子技术员  阅读(12)  评论(0编辑  收藏  举报  来源