將 1-100 所有正整數存入 List<Integer>,移除索引位置為 10的元素(即數字 11),輸出集合長度與剩餘元素(每 10 個換行)。
import java.util.*;
public class CollectionExercise {
public static void main(String[] args) {
// 1. 創建 ArrayList 並填充 1-100
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
list.add(i);
}
// 2. 移除索引 10 的元素(第 11 個數字)
list.remove(10); // remove(int index) 刪除指定位置
// 3. 輸出結果
System.out.println("集合長度 = " + list.size()); // 99
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + "\t");
if (list.get(i) % 10 == 0) System.out.println(); // 每 10 的倍數換行
}
}
}
| 方法 | 說明 | 本例行為 |
|---|---|---|
list.add(i) | 尾部添加 | 按序存入 1..100 |
list.remove(10) | 按索引刪除 | 刪除元素 11(索引 0 基礎) |
list.remove(Object) | 按值刪除首個匹配 | 若寫 list.remove(10) 且泛型為 Integer,會觸發「按索引」重載,而非刪除值 10 |
list.get(i) | 隨機訪問 O(1) | 遍歷輸出 |
remove(int) vs remove(Object)List<Integer> lst = new ArrayList<>(Arrays.asList(1,2,3,10,11)); lst.remove(10); // 刪除索引 10 → IndexOutOfBoundsException (size=5) lst.remove(Integer.valueOf(10)); // 刪除值 10 → 成功,剩餘 [1,2,3,11]
規則:List<Integer> 因泛型擦除,remove(10) 匹配 remove(int index)。需刪除值時顯式包裝 Integer.valueOf(10) 或 (Integer)10。
集合長度 = 99 1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
注意:數字 11(原索引 10)已消失,其餘順序不變。
LinkedList 對比插入/刪除性能。Iterator 邊遍歷邊刪除所有偶數。Stream API 一行完成:IntStream.rangeClosed(1,100).boxed().filter(i->i!=11).collect(Collectors.toList())。掌握 List 索引與值刪除的區別,是 Java 集合操作避坑的基礎功。