Cả ArrayList và LinkedList implement interface List, cung cấp 2 biến thể remove():
1. E remove(int index) - Xóa theo vị trí
- Trả về element bị xóa.
- Ném
IndexOutOfBoundsExceptionnếu index không hợp lệ.
ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
System.out.println(list.remove(0)); // "A" - xóa index 0
System.out.println(list.remove(2)); // "D" - index 2 của list còn lại [B, C, D]
// Kết quả list: [B, C]
2. boolean remove(Object o) - Xóa theo giá trị
- Xóa phần tử đầu tiên khớp với
equals(). - Trả về
truenếu xóa thành công,falsenếu không tìm thấy.
ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "B"));
System.out.println(list.remove("B")); // true - xóa "B" đầu tiên
System.out.println(list); // [A, C, B]
3. Iterator.remove() - Xóa an toàn khi duyệt
Cách duy nhất an toàn để xóa phần tử trong khi đang iterate (tránh ConcurrentModificationException).
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.equals("B")) {
it.remove(); // An toàn
}
}
Ví dụ tổng hợp
import java.util.*;
public class RemoveDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
// Xóa index
list.remove(0); // [B, C, D]
// Xóa object
list.remove("C"); // [B, D]
// Xóa khi iterate
Iterator<String> it = list.iterator();
while (it.hasNext()) {
if (it.next().equals("B")) it.remove();
}
// [D]
}
}
Lưu ý: LinkedList có thêm removeFirst(), removeLast(), pop(), poll() cho thao tác queue/deque hiệu quả hơn.