Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีลบ Element จาก ArrayList หรือ LinkedList ใน Java

ทั้ง ArrayList และ LinkedList implements List Interface มีเมธอด remove() 2 รูปแบบ + Iterator.remove()

1. remove(int index) - ลบด้วย Index

  • คืนค่า Element ที่ลบ (E)
  • โยน IndexOutOfBoundsException ถ้า Index ผิด
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
String removed = list.remove(1); // ลบ Index 1 ("B")
System.out.println(removed);     // B
System.out.println(list);        // [A, C, D]

2. remove(Object o) - ลบด้วยค่า (First Occurrence)

  • คืน boolean (true = ลบสำเร็จ, false = ไม่เจอ)
  • ลบแค่ตัวแรกที่เจอเท่านั้น
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "A", "C"));
boolean success = list.remove("A"); // ลบ "A" ตัวแรก
System.out.println(success);        // true
System.out.println(list);           // [B, A, C]

3. Iterator.remove() - ลบระหว่าง Iterate (Safe)

วิธีเดียวที่ปลอดภัยสำหรับการลบขณะ Loop ผ่าน Iterator

List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    String s = it.next();
    if ("B".equals(s)) {
        it.remove(); // Safe! ไม่เกิด ConcurrentModificationException
    }
}
System.out.println(list); // [A, C, D]

เปรียบเทียบ ArrayList vs LinkedList สำหรับ Remove

Operation ArrayList LinkedList
remove(int index) O(n) - Shift Elements O(n) - Traverse to Node
remove(Object) O(n) - Search + Shift O(n) - Search + Unlink
Iterator.remove() O(n) - Shift O(1) - Unlink (Fast!)

ข้อผิดพลาดทั่วไป

// ผิด: ลบขณะ For-Each Loop -> ConcurrentModificationException
for (String s : list) {
    if ("B".equals(s)) list.remove(s); // ERROR!
}

// ถูก: ใช้ Iterator
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    if ("B".equals(it.next())) it.remove();
}

สรุป

  • ลบด้วย Index -> remove(index)
  • ลบด้วยค่า -> remove(object)
  • ลบขณะ Loop -> ต้องใช้ Iterator.remove()
  • LinkedList เร็วกว่าใน Iterator.remove() (O(1) vs O(n))