全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

java  Iterator接口和LIstIterator接口分析

java  Iterator接口和LIstIterator接口分析

目录

1.Iterator接口
2.ListIterator
3.Iterator和ListIterator的区别 

正文

在继续看ArrayList源码之前,先了解Iterator接口和ListIterator接口,下篇文章详细讲解ArrayList是如何实现它们的。

我们知道,接口只是一种规范,当继承接口并实现其中的方法时,要遵循接口对方法的说明。

1.Iterator接口

Iterator接口取代了Java集合框架中的Enumeratrion。Iterators不同于enumerations的地方主要有两点:

  Iterators允许调用者在迭代过程中从集合里移除元素;

  方法名得到了改善。

Iterator源码如下:

/**
 * 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:
 * Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
 * Method names have been improved.
 * This interface is a member of the Java Collections Framework.
 * @param <E> the type of elements returned by this iterator*/
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());
  }
}

Iterator接口定义了四个方法以及各个方法的功能,如果有类实现了这个接口,且实现了这些方法,这方法需要实现定义的功能,遵循这些规则:

  1).hasNext() 判断容器是否有下一个元素,有则返回true;

  2).next() 返回容器中的下一个元素;

  3).remove() 移除当前迭代器返回的最后一个元素。这个方法在每次调用next()方法之后只能调用一次;

  4).Java 8 增加forEachRemaining方法,它可以实现对余下的所有元素执行指定的操作。

更详细的说明请阅读源码中的注释。

2.ListIterator

ListIterator在Iterator基础上提供了add、set、previous等对列表的操作。但是ListIterator跟Iterator一样,仍是在原列表上进行操作。

ListIterator源码如下:

/**
 * 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 {@code ListIterator}
 * has no current element; its <I>cursor position</I> always
 * lies between the element that would be returned by a call
 * to {@code previous()} and the element that would be
 * returned by a call to {@code next()}.
 * An iterator for a list of length {@code n} has {@code n+1} possible
 * cursor positions, as illustrated by the carets ({@code ^}) below:
 * <PRE>
 *           Element(0)  Element(1)  Element(2)  ... Element(n-1)
 * cursor positions: ^      ^      ^      ^         ^
 * </PRE>
 * Note that the {@link #remove} and {@link #set(Object)} methods are
 * <i>not</i> defined in terms of the cursor position; they are defined to
 * operate on the last element returned by a call to {@link #next} or
 * {@link #previous()}.
 *
 * This interface is a member of the Java Collections Framework.*/
public interface ListIterator<E> extends Iterator<E> {
  // Query Operations

  /**
   * Returns {@code true} if this list iterator has more elements when
   * traversing the list in the forward direction. (In other words,
   * returns {@code true} if {@link #next} would return an element rather
   * than throwing an exception.)
   *
   * @return {@code true} if the list iterator has more elements when
   *     traversing the list in the forward direction
   */
  boolean hasNext();

  /**
   * Returns the next element in the list and advances the cursor position.
   * This method may be called repeatedly to iterate through the list,
   * or intermixed with calls to {@link #previous} to go back and forth.
   * (Note that alternating calls to {@code next} and {@code previous}
   * will return the same element repeatedly.)
   *
   * @return the next element in the list
   * @throws NoSuchElementException if the iteration has no next element
   */
  E next();

  /**
   * Returns {@code true} if this list iterator has more elements when
   * traversing the list in the reverse direction. (In other words,
   * returns {@code true} if {@link #previous} would return an element
   * rather than throwing an exception.)
   *
   * @return {@code true} if the list iterator has more elements when
   *     traversing the list in the reverse direction
   */
  boolean hasPrevious();

  /**
   * Returns the previous element in the list and moves the cursor
   * position backwards. This method may be called repeatedly to
   * iterate through the list backwards, or intermixed with calls to
   * {@link #next} to go back and forth. (Note that alternating calls
   * to {@code next} and {@code previous} will return the same
   * element repeatedly.)
   *
   * @return the previous element in the list
   * @throws NoSuchElementException if the iteration has no previous
   *     element
   */
  E previous();

  /**
   * Returns the index of the element that would be returned by a
   * subsequent call to {@link #next}. (Returns list size if the list
   * iterator is at the end of the list.)
   *
   * @return the index of the element that would be returned by a
   *     subsequent call to {@code next}, or list size if the list
   *     iterator is at the end of the list
   */
  int nextIndex();

  /**
   * Returns the index of the element that would be returned by a
   * subsequent call to {@link #previous}. (Returns -1 if the list
   * iterator is at the beginning of the list.)
   *
   * @return the index of the element that would be returned by a
   *     subsequent call to {@code previous}, or -1 if the list
   *     iterator is at the beginning of the list
   */
  int previousIndex();


  // Modification Operations

  /**
   * Removes from the list the last element that was returned by {@link
   * #next} or {@link #previous} (optional operation). This call can
   * only be made once per call to {@code next} or {@code previous}.
   * It can be made only if {@link #add} has not been
   * called after the last call to {@code next} or {@code previous}.
   *
   * @throws UnsupportedOperationException if the {@code remove}
   *     operation is not supported by this list iterator
   * @throws IllegalStateException if neither {@code next} nor
   *     {@code previous} have been called, or {@code remove} or
   *     {@code add} have been called after the last call to
   *     {@code next} or {@code previous}
   */
  void remove();

  /**
   * Replaces the last element returned by {@link #next} or
   * {@link #previous} with the specified element (optional operation).
   * This call can be made only if neither {@link #remove} nor {@link
   * #add} have been called after the last call to {@code next} or
   * {@code previous}.
   *
   * @param e the element with which to replace the last element returned by
   *     {@code next} or {@code previous}
   * @throws UnsupportedOperationException if the {@code set} operation
   *     is not supported by this list iterator
   * @throws ClassCastException if the class of the specified element
   *     prevents it from being added to this list
   * @throws IllegalArgumentException if some aspect of the specified
   *     element prevents it from being added to this list
   * @throws IllegalStateException if neither {@code next} nor
   *     {@code previous} have been called, or {@code remove} or
   *     {@code add} have been called after the last call to
   *     {@code next} or {@code previous}
   */
  void set(E e);

  /**
   * Inserts the specified element into the list (optional operation).
   * The element is inserted immediately before the element that
   * would be returned by {@link #next}, if any, and after the element
   * that would be returned by {@link #previous}, if any. (If the
   * list contains no elements, the new element becomes the sole element
   * on the list.) The new element is inserted before the implicit
   * cursor: a subsequent call to {@code next} would be unaffected, and a
   * subsequent call to {@code previous} would return the new element.
   * (This call increases by one the value that would be returned by a
   * call to {@code nextIndex} or {@code previousIndex}.)
   *
   * @param e the element to insert
   * @throws UnsupportedOperationException if the {@code add} method is
   *     not supported by this list iterator
   * @throws ClassCastException if the class of the specified element
   *     prevents it from being added to this list
   * @throws IllegalArgumentException if some aspect of this element
   *     prevents it from being added to this list
   */
  void add(E e);
}

ListIterator的功能更加强大,定义的方法有:

  1).hasNext() 向前遍历时,如果有下一个元素返回真;

  2).next() 返回下一个元素的值,并将指针加1;

  3).hasPrevious() 向相反方向遍历时,如果还有元素返回真;

  4).previous() 返回上一个元素的值,并将指针前移1;

  5).nextIndex() 返回此时调用next()方法时返回的元素的索引;

  6).previousIndex() 返回此时调用previous()方法时返回的元素的索引;

  7).remove() 移除最近一次调用next()或previous()方法返回的元素(可选);

  8).set(E e) 用元素e将如果此时调用next()或previous()方法返回的元素替换掉;

  9).add(E e) 添加元素到此时调用next()返回的元素之前,或此时调用previous()返回的元素之后。

更详细的说明请阅读源码中的注释。

3.Iterator和ListIterator的区别

  Iterator和ListIterator的方法对比如下表:

Iterator

ListIterator

 

hasNext()

hasNext() 覆盖

next()

next() 覆盖

remove()

remove() 覆盖

forEachRemaining(Consumer<? super E> action)

forEachRemaining(Consumer<? super E> action) 继承
  hasPrevious()  
  previous()  
  nextIndex()  
  previousIndex()  
  set(E e)  
  add(E e)  

二者的不同之处主要有:

  1).Iterator只能单向移动,ListIterator可以双向移动;

  2).ListIterator可以删除、替换或添加元素,而Iterator只能删除元素;

  3).ListIterator可以返回当前(调用next()或previous()返回的)元素的索引,而Iterator不能。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


# java  # Iterator接口和LIstIterator接口  # Iterator接口和LIstIterator接口源码比较  # 详解JAVA中ListIterator和Iterator的辨析  # java中Iterator和ListIterator实例详解  # Java中的List接口实现类解析  # java中List接口与实现类介绍  # Java for循环和foreach循环的性能对比分析  # java foreach循环为什么不能赋值的讲解  # 为什么在foreach循环中JAVA集合不能添加或删除元素  # Java List接口与Iterator接口及foreach循环使用解析  # 移除  # 并将  # 实现了  # 迭代  # 是在  # 基础上  # 希望能  # 它可以  # 可选  # 谢谢大家  # 如何实现  # 下表  # 过程中  # 不同之处  # 表上  # 有两点  # 得到了  # 前移  # 主要有  # 调用者 


相关文章: 如何在阿里云服务器自主搭建网站?  建站VPS能否同时实现高效与安全翻墙?  如何通过虚拟主机快速完成网站搭建?  武清网站制作公司,天津武清个人营业执照注销查询系统网站?  如何通过智能用户系统一键生成高效建站方案?  长沙做网站要多少钱,长沙国安网络怎么样?  建站主机SSH密钥生成步骤及常见问题解答?  如何基于PHP生成高效IDC网络公司建站源码?  邀请函制作网站有哪些,有没有做年会邀请函的网站啊?在线制作,模板很多的那种?  建站之星安装后如何配置SEO及设计样式?  如何在香港服务器上快速搭建免备案网站?  如何用VPS主机快速搭建个人网站?  建站之星伪静态规则如何设置?  网站视频制作书签怎么做,ie浏览器怎么将网站固定在书签工具栏?  重庆网站制作公司哪家好,重庆中考招生办官方网站?  品牌网站制作公司有哪些,买正品品牌一般去哪个网站买?  如何获取开源自助建站系统免费下载链接?  建站主机服务器选型指南与性能优化方案解析  Java解压缩zip - 解压缩多个文件或文件夹实例  广州网站制作公司哪家好一点,广州欧莱雅百库网络科技有限公司官网?  宝塔新建站点为何无法访问?如何排查?    如何制作算命网站,怎么注册算命网站?  如何用手机制作网站和网页,手机移动端的网站能制作成中英双语的吗?  python的本地网站制作,如何创建本地站点?  c++23 std::expected怎么用 c++优雅处理函数错误返回【详解】  如何在IIS服务器上快速部署高效网站?  企业微网站怎么做,公司网站和公众号有什么区别?  郑州企业网站制作公司,郑州招聘网站有哪些?  婚礼视频制作网站,学习*后期制作的网站有哪些?  电商网站制作公司有哪些,1688网是什么意思?  制作网站哪家好,cc、.co、.cm哪个域名更适合做网站?  广州网站制作的公司,现在专门做网站的公司有没有哪几家是比较好的,性价比高,模板也多的?  建站主机空间推荐 高性价比配置与快速部署方案解析  常州企业建站如何选择最佳模板?  宿州网站制作公司兴策,安徽省低保查询网站?  建站之星多图banner生成与模板自定义指南  制作证书网站有哪些,全国城建培训中心证书查询官网?  国美网站制作流程,国美电器蒸汽鍋怎么用官方网站?  一键制作网站软件下载安装,一键自动采集网页文档制作步骤?  高防服务器租用如何选择配置与防御等级?  大连网站制作公司哪家好一点,大连买房网站哪个好?  潮流网站制作头像软件下载,适合母子的网名有哪些?  如何在IIS中新建站点并配置端口与物理路径?  如何在Golang中使用replace替换模块_指定本地或远程路径  北京网站制作的公司有哪些,北京白云观官方网站?  成都品牌网站制作公司,成都营业执照年报网上怎么办理?  如何快速搭建自助建站会员专属系统?  如何在香港免费服务器上快速搭建网站?  小视频制作网站有哪些,有什么看国内小视频的网站,求推荐? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。