Java ListIterator 接口

ListIterator接口的Java集合框架提供了访问list元素的功能。

它是双向的。这意味着它允许我们沿着两个方向遍历列表的元素。

它扩展了Iterator接口。

The ListIterator interface extends the Java Iterator interface.

List接口提供了一个listIterator()方法,该方法返回ListIterator接口的实例。


ListIterator的方法

ListIterator接口提供了可用于对列表元素执行各种操作的方法。

  • hasNext() - 如果列表中存在元素,则返回true
  • next() - 返回列表的下一个元素
  • nextIndex()返回next()方法将返回的元素的索引
  • previous() - 返回列表的先前元素
  • previousIndex() - 返回previous()方法将返回的元素的索引
  • remove() - 删除由next()previous()返回的元素
  • set() - 用指定元素替换由next()previous()返回的元素

示例1:ListIterator的实现

在下面的示例中,我们在array list中实现了ListIterator接口的next()nextIndex()hasNext()方法。

import java.util.ArrayList;
import java.util.ListIterator;

class Main {
    public static void main(String[] args) {
        // Creating an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(3);
        numbers.add(2);
        System.out.println("ArrayList: " + numbers);

        // Creating an instance of ListIterator
        ListIterator<Integer> iterate = numbers.listIterator();

        // Using the next() method
        int number1 = iterate.next();
        System.out.println("Next Element: " + number1);

        // Using the nextIndex()
        int index1 = iterate.nextIndex();
        System.out.println("Position of Next Element: " + index1);

        // Using the hasNext() method
        System.out.println("Is there any next element? " + iterate.hasNext());
    }
}

输出

ArrayList: [1, 3, 2]
Next Element: 1
Position of Next Element: 1
Is there any next element? true

示例2:ListIterator的实现

在下面的示例中,我们在array list中实现了ListIterator接口的previous()previousIndex()方法。

import java.util.ArrayList;
import java.util.ListIterator;

class Main {
    public static void main(String[] args) {
        // Creating an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(3);
        numbers.add(2);
        System.out.println("ArrayList: " + numbers);

        // Creating an instance of ListIterator
        ListIterator<Integer> iterate = numbers.listIterator();
        iterate.next();
        iterate.next();

        // Using the previous() method
        int number1 = iterate.previous();
        System.out.println("Previous Element: " + number1);

        // Using the previousIndex()
        int index1 = iterate.previousIndex();
        System.out.println("Position of the Previous element: " + index1);
    }
}

输出

ArrayList: [1, 3, 2]
Previous Element: 3
Position of the Previous Element: 0

在上面的示例中,最初,Iterator的实例在1之前。由于1之前没有元素,调用previous()方法将抛出异常。

然后我们使用了2次的next()方法。现在Iterator的实例将在3和2之间。

因此,previous()方法返回3。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战