Java中的Iterator用法

迭代器定义:

  迭代器是一种设计模式,它是一个对象。迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式,迭代器模式属于行为型模式。这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。

迭代器功能:Java中的Iterator功能简单,并且只能单向移动遍历

  (1)iterator()方法:容器使用iterator()返回一个Iterator。

      注意:iterator()方法是java.lang.Iterable接口,被Collection继承。

    (2)next()方法:使用next()获得序列中的下一个元素。

  (3)hasNext():使用hasNext()检查序列中是否还有元素。

  (4)remove():使用remove()将迭代器新返回的元素删除。

Iterator接口源码:

package java.util;

import java.util.function.Consumer;

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());

    }

  }
}

猜你喜欢

转载自www.cnblogs.com/InsaneMachine/p/9901736.html