📜  Java中的列表迭代器

📅  最后修改于: 2022-05-13 01:54:38.935000             🧑  作者: Mango

Java中的列表迭代器

ListIterator是四个Java游标之一。它是一个Java迭代器,用于遍历所有类型的列表,包括 ArrayList、Vector、LinkedList、Stack 等。它从Java 1.2开始可用。它扩展了 迭代器接口。

ListIterator 的层次结构

Java 中的 ListIterator 层次结构

关于 ListIterator 的一些要点

  • 它对于列出实现的类很有用。
  • 从Java 1.2 开始可用。
  • 它支持双向遍历。即向前和向后方向。
  • 它支持所有四种 CRUD 操作(创建、读取、更新、删除)。

关于 ListIterator 的有趣事实

ListIterator 中没有当前元素。它的光标总是位于前一个和下一个元素之间。 previous()将返回到前一个元素, next()将返回到下一个元素。因此,对于一个长度为 n 的列表,有 n+1 个可能的游标。

lisiterator 游标

宣言:

public interface ListIterator extends Iterator

其中E代表泛型类型,即任何类型/用户定义对象的任何参数。

获取列表上的列表迭代器的语法:

ListIterator listIterator()  

这将返回列表中所有元素的列表迭代器。

例子:

Java
// java program to show the usage of listIterator
  
import java.util.*;
  
public class ListIteratorDemo {
    public static void main(String[] args)
    {
          // create a list of names
        List names = new LinkedList<>();
        names.add("Welcome");
        names.add("To");
        names.add("Gfg");
  
        // Getting ListIterator
        ListIterator namesIterator
            = names.listIterator();
  
        // Traversing elements
        while (namesIterator.hasNext()) {
            System.out.println(namesIterator.next());
        }
  
        // for-each loop creates Internal Iterator here.
        for (String s : names) {
            System.out.println(s);
        }
    }
}


Java
// java program to traverse the list both in forward and
// backward direction using listIterator
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
          // list of names
        List names = new LinkedList<>();
        names.add("learn");
        names.add("from");
        names.add("Geeksforgeeks");
  
        // Getting ListIterator
        ListIterator listIterator
            = names.listIterator();
  
        // Traversing elements
        System.out.println("Forward Direction Iteration:");
        while (listIterator.hasNext()) {
            System.out.println(listIterator.next());
        }
  
        // Traversing elements, the iterator is at the end
        // at this point
        System.out.println("Backward Direction Iteration:");
        while (listIterator.hasPrevious()) {
            System.out.println(listIterator.previous());
        }
    }
}


输出
Welcome
To
Gfg
Welcome
To
Gfg

ListIterator 是一个双向迭代器。对于这个功能,它有两种方法:

1. 正向迭代

  • hasNext():在向前遍历时,当列表有更多元素要遍历时,此方法返回true
  • next():此方法返回列表的下一个元素并前进光标的位置。
  • nextIndex():此方法返回调用 next()函数时将返回的元素的索引。

2. 反向迭代

  • hasPrevious():当列表有更多元素要遍历时,该方法返回true,同时反向遍历
  • previous():此方法返回列表的前一个元素并将光标向后移动一个位置。
  • previousIndex():此方法返回调用 previous()函数时将返回的元素的索引。

使用列表迭代器显示前向和后向迭代的示例代码:

Java

// java program to traverse the list both in forward and
// backward direction using listIterator
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
          // list of names
        List names = new LinkedList<>();
        names.add("learn");
        names.add("from");
        names.add("Geeksforgeeks");
  
        // Getting ListIterator
        ListIterator listIterator
            = names.listIterator();
  
        // Traversing elements
        System.out.println("Forward Direction Iteration:");
        while (listIterator.hasNext()) {
            System.out.println(listIterator.next());
        }
  
        // Traversing elements, the iterator is at the end
        // at this point
        System.out.println("Backward Direction Iteration:");
        while (listIterator.hasPrevious()) {
            System.out.println(listIterator.previous());
        }
    }
}
输出
Forward Direction Iteration:
learn
from
Geeksforgeeks
Backward Direction Iteration:
Geeksforgeeks
from
learn

ArrayList 迭代器方法

A. listIterator()

Java.util.ArrayList类的 listIterator() 方法用于返回此列表中元素的列表迭代器(以适当的顺序)。返回的列表迭代器是快速失败的。

句法:

public ListIterator listIterator()

返回值:此方法返回此列表中元素的列表迭代器(以适当的顺序)。

B.) listIterator(int index)

此 listIterator(int index) 方法用于返回列表中元素的列表迭代器(以适当的顺序),从列表中的指定位置开始。指定的索引指示将通过对 next 的初始调用返回的第一个元素。对 previous 的初始调用将返回指定索引减一的元素。返回的列表迭代器是快速失败的。

句法:

public ListIterator listIterator(int index)

参数:此方法将第一个元素的索引作为参数从列表迭代器返回(通过调用 next)

返回值:此方法返回列表中元素的列表迭代器(以适当的顺序),从列表中的指定位置开始。

异常:如果索引超出范围(索引大小()),则此方法抛出IndexOutOfBoundsException

好处:

  • 它支持所有四种 CRUD(创建、读取、更新、删除)操作。
  • 它支持双向遍历,即前向和后向迭代。
  • 易于使用的简单方法名称。

限制:

  • 此迭代器仅用于列表实现类。
  • 不是通用光标。
  • 并非适用于所有集合 API。
  • 列表迭代器不支持元素的并行迭代。
  • listiterator 不支持多元素迭代的良好性能。

迭代器与列表迭代器

相似之处:

  • 它们都是在Java 1.2 中引入的。
  • 它们都用于迭代列表。
  • 它们都支持前向遍历。
  • 它们都支持 READ 和 DELETE 操作。

区别:

                Iterator

                                           ListIterator

It can traverse a collection of any type. It traverses only list collection implemented classes like LinkedList, ArrayList etc.
Traversal can only be done in forward direction.Traversal of elements can be done in both forward and backward direction.
Iterator object can be created by calling iterator() method of the collection class.ListIterator object can be created by calling directions listIterator() method of the collection class.
Deletion of elements is not allowed.Deletion of elements is allowed.
It throws ConcurrentModificationException on doing addition operation. Hence, addition is not allowed. Addition of elements is allowed.
In iterator, we can’t access the index of the traversed element.In listIterator, we have nextIndex() and nextPrevious() methods for accessing the indexes of the traversed or the next traversing element.
Modification of any element is not allowed.Modification is allowed.

ListIterator 的方法

Method

Description

void add(E e)This method inserts the specified element in the list.
boolean hasNext(),This returns true if the list has more elements to traverse.
boolean hasPrevious()This returns true if the list iterator has more elements while traversing the list in the backward direction.
E next()This method returns the next element and increases the cursor by one position.
int nextIndex()This method returns the index of the element which would be returned on calling the next() method.
E previous()This method returns the previous element of the list and shifts the cursor one position backwards.
int previousIndex()This method returns the index of the element which would be returned on calling the previous() method.
void remove()This method removes the last element from the list that was returned on calling next() or previous() method element from.
void set(E e)This method replaces the last element that was returned on calling next() or previous() method with the specified element.

在接口Java中声明的方法。 util.Iterator

Method

Description

default void forEachRemaining​(Consumer action)Performs the given action for each remaining element until all elements have been processed or the action throws an exception.

参考: Java : Java