使用Java中的ListIterator迭代LinkedList元素


ListIterator可用於正向和反向遍歷LinkedList中的元素。

在ListIterator中,hasNext( )方法在正向遍歷LinkedList時,如果還有更多元素則返回true,否則返回false。next( )方法返回LinkedList中的下一個元素,並向前移動遊標位置。

在ListIterator中,hasPrevious( )方法在反向遍歷LinkedList時,如果還有更多元素則返回true,否則返回false。previous( )方法返回LinkedList中的前一個元素,並將遊標位置向後移動。

下面給出一個演示此功能的程式。

示例

 線上演示

import java.util.ListIterator;
import java.util.LinkedList;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Andy");
      l.add("Sara");
      l.add("James");
      l.add("Betty");
      l.add("Bruce");
      ListIterator li = l.listIterator();
      System.out.println("The LinkedList elements in the forward direction are: ");
      while (li.hasNext()) {
         System.out.println(li.next());
      }
      System.out.println("
The LinkedList elements in the reverse direction are: ");       while (li.hasPrevious()) {          System.out.println(li.previous());       }    } }

輸出

上述程式的輸出如下:

The LinkedList elements in the forward direction are:
Andy
Sara
James
Betty
Bruce

The LinkedList elements in the reverse direction are:
Bruce
Betty
James
Sara
Andy

現在讓我們理解一下上面的程式。

建立LinkedList,並使用LinkedList.add()將元素新增到LinkedList中。下面是一個演示此功能的程式碼片段

LinkedList<String> l = new LinkedList<String>();

l.add("Andy");
l.add("Sara");
l.add("James");
l.add("Betty");
l.add("Bruce");

然後使用ListIterator介面正向和反向顯示LinkedList元素。下面是一個演示此功能的程式碼片段

ListIterator li = l.listIterator();
System.out.println("The LinkedList elements in the forward direction are: ");
while (li.hasNext()) {
   System.out.println(li.next());
}
System.out.println("
The LinkedList elements in the reverse direction are: "); while (li.hasPrevious()) {    System.out.println(li.previous()); }

更新於: 2020年6月29日

202 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.