Iterator与Enumeration

Enumeration的存在有什么意义?

Iterator已经实现了对容器的遍历了,Enumeration的存在有什么意义呢?

原因可能有很多种,个人了解有限,欢迎大家补充。

  1. Enumeration在JDK 1.0就已经存在了,而Iterator是JDK 2.0新加的接口。为了依赖JDK1.0写的代码能够正常运行,Enumeration是不能删的。

相同点

  • Iterator和Enumeration都可以对某些容器进行遍历。
  • Iterator和Enumeration都是接口。

欢迎大家补充。

不同点

  • Iterator有对容器进行修改的方法。而Enumeration只能遍历。
  • Iterator支持fail-fast,而Enumeration不支持。
  • Iterator比Enumeration覆盖范围广,基本所有容器中都有Iterator迭代器,而只有Vector、Hashtable有Enumeration。
  • Enumeration在JDK 1.0就已经存在了,而Iterator是JDK2.0新加的接口。

Enumeration例子

import java.util.Enumeration;
import java.util.Vector;

public class ItrOfVectorTest {

        @org.junit.Test
        public void test() {
            Vector list = new Vector<>();
            list.add("1");
            list.add("2");
            list.add("3");
            list.add("4");
            Enumeration enu = list.elements();  
            while (enu.hasMoreElements()) {  
                System.out.println(enu.nextElement());
            }
        }
}

Enumeration方法

  • elements()。vector.elements()用来从容器对象中返回vector中所有元素的Enumeration。
  • hasMoreElements()。检查序列中向下是否还有元素。
  • nextElement()。获取序列的下个元素。

Enumeration在Vector中的实现

/**
 * 返回vector中所有元素的Enumeration。
 * 
 * Enumeration提供用于遍历vector中所有元素的方法
 * 
 * @return  返回vector中所有元素的Enumeration。
 * @see     Iterator
 */
public Enumeration<E> elements() {
    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");
        }
    };
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值