Iterator与Enumeration

来源:互联网 发布:js 判断对象的类型 编辑:程序博客网 时间:2024/06/01 10:11

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");        }    };}
原创粉丝点击