使用 ListIterator 修改清單

Java 的輸入/輸出與串流

Alex Liu

Software Development Engineer

Iterator 與 ListIterator

Iterator 與 ListIterator 比較

Java 的輸入/輸出與串流

範例 ArrayList

import java.util.ArrayList;
public class SampleData {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
    }
}  
[Alice, Bob, Charlie]
Java 的輸入/輸出與串流

用 ListIterator 走訪清單

// Import ListIterator class
import java.util.ListIterator;

// Create ListIterator object for sample list `names` ListIterator<String> it = names.listIterator(); // Use .hasNext() and `.next()` to iterate the list and print line by line while (it.hasNext()) { System.out.println(it.next()); }
Alice 
Bob 
Charlie
Java 的輸入/輸出與串流

ListIterator 的反向走訪

  • 使用 .previous() 往回走訪清單
// Create ListIterator object for sample list `names`
ListIterator<String> it = names.listIterator(names.size());
// Use .hasPrevious() to check if the iterator reach the beginning of the list
while (it.hasPrevious()) {
    // Use .previous() to retrieve the element in reverse order
    System.out.println(it.previous());}
  • 反向列印元素,輸出:
Charlie
Bob
Alice
Java 的輸入/輸出與串流

走訪時修改元素

  • 使用 .set() 方法
// Create ListIterator object for sample list names
ListIterator<String> it = names.listIterator();

// Iterate the list and modify element using .set() while (it.hasNext()) { String name = it.next(); if ("Bob".equals(name)) it.set("Bobby"); }
  • 更新後的 names 清單:
[Alice, Bobby, Charlie]
Java 的輸入/輸出與串流

走訪時新增元素

  • .add() 新增元素
ListIterator<String> it = names.listIterator();

// Iterate the list and insert element using .add() while (it.hasNext()) { String name = it.next(); if ("Charlie".equals(name)) it.add("David"); }
  • 更新後的 names 清單:
    [Alice, Bobby, Charlie, David]
    
Java 的輸入/輸出與串流

重點總結

  • ListIterator 擴充自 Iterator
    • 支援前後雙向走訪
    • 可在迭代時修改元素
  • 重點方法複習

    • .next().previous():前進與後退
    • .set():修改目前元素
    • .add():動態插入元素
    • .remove():安全刪除元素
    • 僅適用於 List(ArrayListLinkedList 等)
Java 的輸入/輸出與串流

一起來練習吧!

Java 的輸入/輸出與串流

Preparing Video For Download...