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 @   一锤子技术员  阅读(16)  评论(0编辑  收藏  举报  
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示