Java の入出力とストリーム
Alex Liu
Software Development Engineer

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]
// ListIterator クラスをインポート import java.util.ListIterator;// サンプルリスト `names` の ListIterator を作成 ListIterator<String> it = names.listIterator(); // .hasNext() と `.next()` で走査し、1行ずつ表示 while (it.hasNext()) { System.out.println(it.next()); }
Alice
Bob
Charlie
.previous() で後方へ移動// サンプルリスト `names` の ListIterator を作成
ListIterator<String> it = names.listIterator(names.size());
// .hasPrevious() で先頭到達を確認
while (it.hasPrevious()) {
// .previous() で逆順に取得
System.out.println(it.previous());}
Charlie
Bob
Alice
.set() メソッドを使用// サンプルリスト names の ListIterator を作成 ListIterator<String> it = names.listIterator();// 反復中に .set() で要素を変更 while (it.hasNext()) { String name = it.next(); if ("Bob".equals(name)) it.set("Bobby"); }
names リスト:[Alice, Bobby, Charlie]
.add() を使用ListIterator<String> it = names.listIterator();// 反復中に .add() で要素を挿入 while (it.hasNext()) { String name = it.next(); if ("Charlie".equals(name)) it.add("David"); }
names リスト:[Alice, Bobby, Charlie, David]
ListIterator は Iterator を拡張主要メソッドまとめ
.next()/.previous(): 前へ/後ろへ移動.set(): 現在要素を変更.add(): 要素を挿入.remove(): 安全に削除ArrayList、LinkedList など)Java の入出力とストリーム