Input/Output และ Streams ใน 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]
// 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
.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
.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]
.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]
ListIterator ขยายความสามารถจาก Iteratorสรุปเมธอดสำคัญ
.next()/.previous(): เลื่อนไปข้างหน้าและย้อนกลับ.set(): แก้ไขสมาชิกปัจจุบัน.add(): แทรกสมาชิกแบบไดนามิก.remove(): ลบสมาชิกได้อย่างปลอดภัยArrayList, LinkedList เป็นต้น)Input/Output และ Streams ใน Java