Java ListIterator - Java 中的 ListIterator
我们知道 Java 有四种游标:枚举、迭代器、列表迭代器和拆分器。我们已经在上一篇文章中讨论了枚举和迭代器游标。在阅读这篇文章之前,请先阅读我之前的文章:Java 迭代器。在这篇文章中,我们将讨论第三个 Java 游标:列表迭代器。
Java 列表迭代器
与 Iterator 一样,ListIterator 是一个 Java 迭代器,用于从 List 实现的对象中逐个迭代元素。
- 它从 Java 1.2 开始可用。
- 它扩展了 Iterator 接口。
- 它仅对 List 实现的类有用。
- 与 Iterator 不同,它支持所有四种操作:CRUD(CREATE、READ、UPDATE 和 DELETE)。
- 与迭代器不同,它同时支持前向迭代和后向迭代。
- 它是一个双向迭代器。
- 它没有当前元素;它的光标位置始终位于调用 previous() 返回的元素与调用 next() 返回的元素之间。
注意:- Collection API 中的 CRUD 操作是什么?
- 创建:向 Collection 对象添加新元素。
- 阅读:从 Collection 对象检索元素。
- 更新:更新或设置 Collection 对象中的现有元素。
- 删除:从 Collection 对象中删除元素。
Java ListIterator 类图
在 Java 中,ListIterator 是 Collection API 中的一个接口。它扩展了 Iterator 接口。为了支持正向和反向迭代以及 CRUD 操作,它具有以下方法。我们可以将此 Iterator 用于所有 List 实现的类,如 ArrayList、CopyOnWriteArrayList、LinkedList、Stack、Vector 等。我们将在接下来的部分中深入探讨这些方法以及一些有用的方法。
Java ListIterator 方法
Java ListIterator 接口具有以下方法。
- void add(E e):将指定元素插入列表。
- boolean hasNext():如果此列表迭代器在向前遍历列表时有更多元素,则返回 true。
- boolean hasPrevious():如果此列表迭代器在反向遍历列表时具有更多元素,则返回 true。
- E next():返回列表中的下一个元素并前进光标位置。
- int nextIndex():返回后续调用 next() 所返回元素的索引。
- E previous():返回列表中的前一个元素,并将光标位置向后移动。
- int previousIndex():返回后续调用 previous() 所返回元素的索引。
- void remove():从列表中删除由 next() 或 previous() 返回的最后一个元素。
- void set(E e):用指定元素替换 next() 或 previous() 返回的最后一个元素。
我们将在接下来的章节中通过有用的示例逐一探讨这些方法。
Java ListIterator Basic Example
In this section, we will discuss some ListIterator methods with some examples. First, we need to understand about how to get this iterator object. How to get ListIterator?
ListIterator<E> listIterator()
It returns a list iterator over the elements in this list. Example:-
import java.util.*;
public class ListIteratorDemo
{
public static void main(String[] args)
{
List<String> names = new LinkedList<>();
names.add("Rams");
names.add("Posa");
names.add("Chinni");
// Getting ListIterator
ListIterator<String> namesIterator = names.listIterator();
// Traversing elements
while(namesIterator.hasNext()){
System.out.println(namesIterator.next());
}
// Enhanced for loop creates Internal Iterator here.
for(String name: names){
System.out.println(name);
}
}
}
Output:-
Rams
Posa
Chinni
ListIterator Bi-Directional Iteration Example
In section, we will explore how ListIterator’s methods work to perform Forward Direction and Backward Direction iterations.
import java.util.*;
public class BiDirectinalListIteratorDemo
{
public static void main(String[] args)
{
List<String> names = new LinkedListt<>();
names.add("Rams");
names.add("Posa");
names.add("Chinni");
// Getting ListIterator
ListIterator<String> 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());
}
}
}
Output:-
Forward Direction Iteration:
Rams
Posa
Chinni
Backward Direction Iteration:
Chinni
Posa
Rams
Types of Java Iterators
As we know Java has four cursors: Enumeration, Iterator, ListIterator, and Spliterator. We can categorize them into two main types as shown below:
- Uni-Directional Iterators They are Cursors which supports only Forward Direction iterations. For instance, Enumeration, Iterator, etc. are Uni-Directional Iterators.- Bi-Directional Iterators They are Cursors which supports Both Forward Direction and Backward Direction iterations. For instance, ListIterator is Bi-Directional Iterator.
How Java ListIterator Works Internally?
As we know, Java ListIterator works in both directions that mean it works in the forward direction as well as backward direction. It is a Bi-directional Iterator. To support this functionality, it has two sets of methods.
- Forward Direction Iteration methods We need to use the following methods to support Forward Direction Iteration:
- hasNext())
- next()
- nextIndex()
- Backward Direction Iteration methods We need to use the following methods to support Backward Direction Iteration:
- hasPrevious()
- previous()
- previousIndex()
In my previous post, we have already discussed how an Iterator works internally in forwarding Direction at “How Java Iterator Works Internally?” section. Even ListIterator also works in that same way. If you want go through my previous post, please click here: Java Iterator. In this section, we will discuss how ListIterator works in Backward Direction. Let us take the following LinkedList object to understand this functionality.
List<String> names = new LinkedList<>();
names.add("E-1");
names.add("E-2");
names.add("E-3");
.
.
.
names.add("E-n");
Now create a ListIterator object on LinkedList as shown below:
ListIterator<String> namesIterator = names.listLterator();
Let us assume “namesIterator” ListIterator looks like below: Here ListIterator’s Cursor is pointing to the before the first element of the List. Now we run the following code snippet in the while loop.
namesIterator.hasNext();
namesIterator.next();
When we run the above code snippet in the while loop, ListIterator’s Cursor points to the last element in the LinkedList. Then we can run the following code snippet to start traversing from the end to the start.
namesIterator.hasPrevious();
namesIterator.previous();
When we run the above code snippet, ListIterator’s Cursor points to the “Last but one” element in the List as shown in the above diagram. Do this process to reach the ListIterator’s Cursor to the first element of the LinkedList. After reading the first element, if we run the below code snippet, it returns “false” value.
namesIterator.hasPrevious();
As ListIterator’s Cursor points to the before the first element of the LinkedList, hasPrevious() method returns a false value. After observing all these diagrams, we can say that Java ListIterator supports Both Forward Direction and Backward Direction Iterations as shown in the below diagrams. So it is also known as Bi-Directional Cursor. Forward Direction ListIterator Backward Direction ListIterator
Advantages of ListIterator
Unlike Iterator, ListIterator has the following advantages:
- Like Iterator, it supports READ and DELETE operations.
- It supports CREATE and UPDATE operations too.
- That means, it supports CRUD operations: CREATE, READ, UPDATE and DELETE operations.
- It supports both Forward direction and Backward direction iteration. That means it’s a Bi-Directional Java Cursor.
- Method names are simple and easy to use them.
Limitations of ListIterator
Compare to Iterator, Java ListIterator has many advantages. However, it still have the following some limitations.
- It is an Iterator only List implementation classes.
- Unlike Iterator, it is not applicable for whole Collection API.
- It is not a Universal Java Cursor.
- Compare to Spliterator, it does NOT support Parallel iteration of elements.
- Compare to Spliterator, it does NOT support better performance to iterate large volume of data.
Similarities between Iterator and ListIterator
In this section, we will discuss about Similarities between Java two Cursors: Iterator and ListIterator.
- Bother are introduced in Java 1.2.
- Both are Iterators used to iterate Collection or List elements.
- Both supports READ and DELETE operations.
- Both supports Forward Direction iteration.
- Both are not Legacy interfaces.
Differences between Iterator and ListIterator
In this section, we sill discuss differences between Java Two Iterators: Iterator and ListIterator.
Iterator | ListIterator |
---|---|
Introduced in Java 1.2. | Introduced in Java 1.2. |
It is an Iterator for whole Collection API. | It is an Iterator for only List implemented classes. |
It is an Universal Iterator. | It is NOT an Universal Iterator. |
It supports only Forward Direction Iteration. | It supports both Forward and Backward Direction iterations. |
It’s a Uni-Directional Iterator. | It’s a Bi-Directional Iterator. |
It supports only READ and DELETE operations. | It supports all CRUD operations. |
We can get Iterator by using iterator() method. | We can ListIterator object using listIterator() method. |
That’s all of about ListIterator in Java. I hope these Java ListIterator theories and examples will help you in getting started with ListIterator programming. Reference: ListIterator API Doc