美文网首页
java学习笔记---迭代器(Iterator)

java学习笔记---迭代器(Iterator)

作者: Tank_Mao | 来源:发表于2020-09-12 17:32 被阅读0次

若有不对的地方,欢迎各位大佬批评指正!

首先,咱们来看一下Iterator接口的源码!

public interface Iterator<E> {
    boolean hasNext();
    E next();
    default void remove() {
          throw new UnsupportedOperationException("remove");
    }
    default void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            while (hasNext())
            action.accept(next());
    }
}

然后,用我的四级英语水平看一下官方的注释。。。

/**
 * An iterator over a collection.  {@code Iterator} takes the place of
 * {@link Enumeration} in the Java Collections Framework.  Iterators
 * differ from enumerations in two ways:
 *
 * <ul>
 *      <li> Iterators allow the caller to remove elements from the
 *           underlying collection during the iteration with well-defined
 *           semantics.
 *      <li> Method names have been improved.
 * </ul>
 *
 * <p>This interface is a member of the
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 * Java Collections Framework</a>.
 *
 * @param <E> the type of elements returned by this iterator
 *
 * @author  Josh Bloch
 * @see Collection
 * @see ListIterator
 * @see Iterable
 * @since 1.2
 */

Iterator代替了java集合框架中的Enumration,iterators和enumrations有以下两个区别:

(1)在迭代期间,Iterator允许调用者使用定义好的语句删除下层集合的元素;
(2)Enumration的方法名太累赘了,Iterator的方法名更受喜爱。

查看源码可知,Iterator接口中只有4个方法,前三个都比较容易看的懂,下面咱们专门看一下最后一个方法:

    /**
     * Performs the given action for each remaining element until all elements
     * have been processed or the action throws an exception.  Actions are
     * performed in the order of iteration, if that order is specified.
     * Exceptions thrown by the action are relayed to the caller.
     *
     * @implSpec
     * <p>The default implementation behaves as if:
     * <pre>{@code
     *     while (hasNext())
     *         action.accept(next());
     * }</pre>
     *
     * @param action The action to be performed for each element
     * @throws NullPointerException if the specified action is null
     * @since 1.8
     */

对每个需要处理的元素执行给定的操作,直到所有元素已处理或操作引发异常。如果指定了迭代顺序,则按迭代顺序执行操作。操作引发的异常被中继到调用方。

用我的“四级英语”对官方的注释进行了一系列解读,我明白了,第四个方法是用来对集合元素进行遍历用的!由于此方法要配合lambda表达式使用,等博主学了lambda表达式再来更新!

相关文章

网友评论

      本文标题:java学习笔记---迭代器(Iterator)

      本文链接:https://www.haomeiwen.com/subject/uwpwektx.html