欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java iterator和Iterable的区别

程序员文章站 2024-02-17 21:49:46
...

iterator为Java中的迭代器对象

Iterable是对iterator的一个封装, 以支持for each循环。

 

java iterator和Iterable的区别

 

Iterator<Tuple2<String, String>> el = elements.iterator();

// iterator为Java中的迭代器对象,是能够对List这样的集合进行迭代遍历的底层依赖
// 而Iterable接口里定义了iterator的方法,相当于对iterator的封装,支持for each循环

// iterator 不支持for each循环
for (Tuple2<String, String> e: el){

}

// Iterable 支持for each循环
Tuple2<String, String> ret = Tuple2.of("", "");
for(Tuple2<String, String> element: elements){
    ret = element;
}


// iterator 循环遍历
while (el.hasNext()){
    Tuple2<String, String> data = el.next();
    System.out.println(data);
}

 

Iterable.java

 

Iterable接口支持for each循环, 然而实现Iterable接口,就必需为foreach语句提供一个迭代器

这个迭代器是用接口定义的 iterator方法提供的。也就是iterator方法需要返回一个Iterator对象。

public interface Iterable<T> {
    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    Iterator<T> iterator();
}

 

Iterator.java

1、每次在迭代前   ,先调用hasNext()探测是否迭代到终点(本次还能再迭代吗?)。

2、next方法不仅要返回当前元素,还要后移游标cursor

3、remove()方法用来删除最近一次已经迭代出的元素

4、 迭代出的元素是原集合中元素的拷贝(重要)

5、配合foreach使用

public interface Iterator<E> {
    /**
     * Returns {@code true} if the iteration has more elements.
     * (In other words, returns {@code true} if {@link #next} would
     * return an element rather than throwing an exception.)
     *
     * @return {@code true} if the iteration has more elements
     */
    boolean hasNext();

    /**
     * Returns the next element in the iteration.
     *
     * @return the next element in the iteration
     * @throws NoSuchElementException if the iteration has no more elements
     */
    E next();

    /**
     * Removes from the underlying collection the last element returned
     * by this iterator (optional operation).  This method can be called
     * only once per call to {@link #next}.  The behavior of an iterator
     * is unspecified if the underlying collection is modified while the
     * iteration is in progress in any way other than by calling this
     * method.
     *
     * @implSpec
     * The default implementation throws an instance of
     * {@link UnsupportedOperationException} and performs no other action.
     *
     * @throws UnsupportedOperationException if the {@code remove}
     *         operation is not supported by this iterator
     *
     * @throws IllegalStateException if the {@code next} method has not
     *         yet been called, or the {@code remove} method has already
     *         been called after the last call to the {@code next}
     *         method
     */
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }

    /**
     * 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
     */
    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

参考: https://www.cnblogs.com/keyi/p/5821285.html