1.使用for循環遍歷集合進行刪除
public static void main(String[] args) {
List<String> strlist = new ArrayList<>();
strlist.add("a");
strlist.add("b");
strlist.add("c");
strlist.add("d");
for (int i = 0; i < strlist.size(); i++) {
strlist.remove(i);
}
System.out.println(strlist);
//結果 [b, d]
}
查看當前代碼結果 輸出爲b,d 只刪除了兩個元素:
循環了幾次:3次
第一次 i=0 , 集合長度 爲4,集合爲: [a, b, c, d], 移除元素 a
第二次 i=1 ,集合長度 爲3, 集合爲: [b, c, d], 移除元素 c (下標爲1的 c)
第三次 i=2 ,集合長度 爲2(結束循環), 集合爲:[b, d]
public static void main(String[] args) {
List<String> strlist = new ArrayList<>();
strlist.add("a");
strlist.add("b");
strlist.add("c");
strlist.add("d");
for (int i = 0; i < strlist.size(); i++) {
strlist.remove(0);
}
System.out.println(strlist);
//結果 [c, d]
}
查看當前代碼結果 輸出爲c,d 只刪除了前兩個元素:
循環了幾次:3次
第一次 i=0 , 集合長度 爲4,集合爲: [a, b, c, d], 移除元素 a
第二次 i=1 ,集合長度 爲3, 集合爲: [b,c, d], 移除元素b
第三次 i=2 ,集合長度 爲2(結束循環), 集合爲:[c, d]
由此可以看出 在循環時 集合的長度在變化,判斷出現錯誤,可以把集合的長度賦一個變量,這樣才能循環4次