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不能。

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

(0)

相关推荐

  • java 中List按照date排序的实现

    java 中List按照date排序的实现 今天开发需要对一个list进行排序,要求对里面的date类型的属性进行排序,不多说,直接上代码. Leavecalendar这个bean类里面有属性date: private Date Date; //有get/set方法: public Date getDate() { return Date; } public void setDate(Date lcDate) { this.Date = lcDate; } 排序我们要用到java里面的Colle

  • java list 比较详解及实例

    java list 比较详解及实例 java里比较两个list的值是否一致,不考虑顺序,有多种方法,比如排序后直接用equals比较,相互之间执行两次containsAll等,这些办法都需要我们给list的元素类实现equals和hashcode方法.但是有一种特殊情况,如果我们并不方便去实习类的equals方法,例如是一个古老的第三方jar包,改代码会带来很多未知问题,这时候该怎么办呢. 其实很简单,万能的apache-commons早就想到了这一点,所以在commons-collection

  • Java中List for循环的6种写法总结(推荐)

    如下所示: List<String> list = new ArrayList<String>(); /** * 方法一:最普通的不加思考的写法 * <p> * 优点:较常见,易于理解 * <p> * 缺点:每次都要计算list.size() */ for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } /** * 方法二:数组长度提取出来 * <p&g

  • Java中ArrayList和LinkedList之间的区别_动力节点Java学院整理

    一.ArrayList ArrayList是一个可以处理变长数组的类型,这里不局限于"数"组,ArrayList是一个泛型类,可以存放任意类型的对象.顾名思义,ArrayList是一个数组列表,因此其内部是使用一个数组来存放对象的,因为Object是一切类型的父类,因而ArrayList内部是有一个Object类型的数组类存放对象.ArrayList类常用的方法有add().clear().get().indexOf().remove().sort().toArray().toStri

  • JAVA中ListIterator和Iterator详解与辨析(推荐)

    在使用Java集合的时候,都需要使用Iterator.但是java集合中还有一个迭代器ListIterator,在使用List.ArrayList.LinkedList和Vector的时候可以使用.这两种迭代器有什么区别呢?下面我们详细分析.这里有一点需要明确的时候,迭代器指向的位置是元素之前的位置. 首先看一下Iterator和ListIterator迭代器的方法有哪些. Iterator迭代器包含的方法有: hasNext():如果迭代器指向位置后面还有元素,则返回 true,否则返回fal

  • Java中List Set和Map之间的区别_动力节点Java学院整理

    Java集合的主要分为三种类型: • Set(集) • List(列表) • Map(映射) 要深入理解集合首先要了解下我们熟悉的数组: 数组是大小固定的,并且同一个数组只能存放类型一样的数据(基本类型/引用类型),而JAVA集合可以存储和操作数目不固定的一组数据. 所有的JAVA集合都位于 java.util包中! JAVA集合只能存放引用类型的的数据,不能存放基本数据类型. 世间上本来没有集合,(只有数组参考C语言)但有人想要,所以有了集合 有人想有可以自动扩展的数组,所以有了List 有的

  • java Iterator接口和LIstIterator接口分析

    java  Iterator接口和LIstIterator接口分析 目录 1.Iterator接口 2.ListIterator 3.Iterator和ListIterator的区别 正文 在继续看ArrayList源码之前,先了解Iterator接口和ListIterator接口,下篇文章详细讲解ArrayList是如何实现它们的. 我们知道,接口只是一种规范,当继承接口并实现其中的方法时,要遵循接口对方法的说明. 1.Iterator接口 Iterator接口取代了Java集合框架中的Enu

  • java  Iterator接口和LIstIterator接口分析

    java  Iterator接口和LIstIterator接口分析 目录 1.Iterator接口 2.ListIterator 3.Iterator和ListIterator的区别 正文 在继续看ArrayList源码之前,先了解Iterator接口和ListIterator接口,下篇文章详细讲解ArrayList是如何实现它们的. 我们知道,接口只是一种规范,当继承接口并实现其中的方法时,要遵循接口对方法的说明. 1.Iterator接口 Iterator接口取代了Java集合框架中的Enu

  • Java Iterator接口遍历单列集合迭代器原理详解

    这篇文章主要介绍了Java Iterator接口遍历单列集合迭代器原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Iterator接口概述 在程序开发中,经常需要遍历集合中的所有元素.针对这种需求,JDK专门提供了一个接口java.util.Iterator . Iterator 接口也是Java集合中的一员,但它与 Collection . Map 接口有所不同,Collection 接口与 Map 接口主要用于存储元素,而 Iter

  • JAVA Iterator接口与增强for循环的实现

    1 Iterator迭代器 1.1 Iterator接口 java.util.Iterator接口也是Java集合中的一员: Iterator主要用于迭代访问(即遍历)Collection中的元素,因此Iterator对象也被称为迭代器. public Iterator iterator(): 获取集合对应的迭代器,用来遍历集合中的元素. 迭代:Collection集合元素的通用获取方式.在取元素之前先判断集合中有没有元素.如果有,就把这个元素取出来:继续判断,如果还有就再取出来:就这样一直把集

  • Java Iterator接口实现代码解析

    Iterator接口 源代码 package java.util; import java.util.function.Consumer; /** * 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:

  • Java List接口与Iterator接口及foreach循环使用解析

    目录 List接口 ArrayList集合 LinkedList集合 Iterator接口 foreach循环 List接口 List接口继承Collection接口,属于单列集合,在List集合中允许出现重复的元素,所有的元素是以一种线性方式进行存储的,在程序中通过索引来访问集合中的指定元素,元素是顺序存储的,即元素的存入顺序和取出顺序一致. ArrayList集合 ArrayList是List接口的一个实现类,在ArrayList内部封装了一个长度可变的数组对象. package 集合类;

  • Java Iterator迭代器_动力节点Java学院整理

    迭代器是一种模式,它可以使得对于序列类型的数据结构的遍历行为与被遍历的对象分离,即我们无需关心该序列的底层结构是什么样子的.只要拿到这个对象,使用迭代器就可以遍历这个对象的内部. 1.Iterator Java提供一个专门的迭代器<<interface>>Iterator,我们可以对某个序列实现该interface,来提供标准的Java迭代器.Iterator接口实现后的功能是"使用"一个迭代器. 文档定义: Package java.util; publici

  • 一文读懂Java Iterator(迭代器)

    Java Iterator(迭代器)不是一个集合,它是一种用于访问集合的方法,可用于迭代 ArrayList和HashSet等集合. Iterator 是 Java 迭代器最简单的实现,ListIterator 是 Collection API 中的接口, 它扩展了 Iterator 接口. 迭代器 it 的两个基本操作是 next .hasNext 和 remove. 调用 it.next() 会返回迭代器的下一个元素,并且更新迭代器的状态. 调用 it.hasNext() 用于检测集合中是否

  • 详谈Enumeration接口和Iterator接口的区别

    如下所示: package java.util; public interface Enumeration<E> { boolean hasMoreElements(); E nextElement(); } public interface Iterator<E> { boolean hasNext(); E next(); void remove(); } (01) 函数接口不同 Enumeration 只有2个函数接口. 通过Enumeration,我们只能读取集合的数据,而

  • Java Http接口加签、验签操作方法

    1.业务背景 最近接触了一些电商业务,发现在处理电商业务接口时,比如淘宝.支付类接口,接口双方为了确保数据参数在传输过程中未经过篡改,都需要对接口数据进行加签,然后在接口服务器端对接口参数进行验签,确保两个签名是一样的,验签通过之后再进行业务逻辑处理.我们这里主要介绍一下处理思路,至于签名算法我不做过多介绍,网上一大堆. 2.处理思路 双方约定好,参数按特定顺序排列,比如按首字母的顺序排列,如url:http://xxx/xxx.do?a=wersd&b=sd2354&c=4&si

随机推荐