Enumeration与Iterator接口

Enumeration接口

 

HashTableVector中的元素遍历都是用的Enumeration接口实现的。

hasMoreElements();//判断Enumeration中是否还有元素

nextElement();//返回下一个元素

 

Iterator 接口

 

An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.
  • 前者是“fail-fast”——fail-fast 机制是java集合(Collection)中的一种错误机制。当多个线程对同一个集合的内容进行操作时,就可能会产生fail-fast事件。例如:当某一个线程A通过iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了;那么线程A访问集合时,就会抛出ConcurrentModificationException异常,产生fail-fast事件
  • 前者可以配合Iterable<E>接口用于Java 5for-each循环中。
  • Iterator适用于边界未知的场景,Enumeration的边界是已知且可枚举的。而且这是两个作用不同的东西。

 方法:

hasNext();
next();
remove();
forEachRemaining(Consumer<? super E> action);

 

最后一个方法相当与给集合的每个元素执行:

while (hasNext())

        action.accept(next());

 

ListIterator接口

继承自Iterator 接口,但新增了几个方法

 

 

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of length n has n+1 possible cursor positions, as illustrated by the carets (^) below:

                          Element(0)   Element(1)   Element(2)   ... Element(n-1)

 cursor positions:      ^              ^              ^              ^                    ^

 

void hasPrevious();//判断游标前面是否有元素;

Object previous();//返回游标前面的元素,同时游标前移一位。游标前没有元素就报 java.util.NoSuchElementException 的错,所以使用前最好判断一下;

int nextIndex();//返回游标后边元素的索引位置,初始为 0 ;遍历 N 个元素结束时为 N;

int previousIndex();//返回游标前面元素的位置,初始时为 -1,同时报 java.util.NoSuchElementException 错;

void add(E);//在游标前面插入一个元素

void set(E);//更新迭代器最后一次操作的元素为 E,也就是更新最后一次调用 next() 或者 previous() 返回的元素。当没有迭代,也就是没有调用 next() 或者 previous() 直接调用 set 时会抛 java.lang.IllegalStateException ;

注意:remove()set(Object)方法不是根据游标的位置来操作的,他们被定义成操作由next()  previous()调用返回的最后一个元素。

 

 

 

 

 

posted @ 2018-04-07 16:07  SleepyDot  阅读(128)  评论(0编辑  收藏  举报