java enumeration接口_Java Enumeration接口详解

二话不说,来看官方文档:

public interface Enumeration

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 elements() {

//通过匿名类方式实现了Enumeration接口

return new Enumeration() {

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 v:

for (Enumeration 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 e = v.elements();

String output = "";

while (e.hasMoreElements()) {

output += e.nextElement() + " ";

}

System.out.println(output);

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值