
package com.itheima.arraylist;import java.util.ArrayList;public class ArrayListTest4 { public static void main(String[] args) { // 目标:学习遍历并删除元素的正确方案 // 1.创建一个ArrayList集合存储一个班级学生的成绩 ArrayList<Integer> scores = new ArrayList<>(); scores.add(98); scores.add(77); scores.add(66); scores.add(89); scores.add(79); scores.add(50); scores.add(100); System.out.println(scores); // 有毛病的代码 // 2.把分数低于80分的成绩从集合中去掉// for (int i = 0; i < scores.size(); i++) {// int score = scores.get(i); // 将每次遍历到的元素赋值给score// if (score < 80){// // 这个分数必须删除// scores.remove(i); // 如果用remove会删除一个元素后,他后面的一个元素会往前移动,索引会发生变化,所以不能用这种方式// }// } //[98, 77, 66, 89, 79, 50, 100]原集合// System.out.println(scores); //[98, 66, 89, 50, 100] // 完美方案之一:// for (int i = 0; i < scores.size(); i++) {// int score = scores.get(i); // 将每次遍历到的元素赋值给score// if (score < 80){// // 这个分数必须删除// scores.remove(i); // 如果用remove会删除一个元素后,他后面的一个元素会往前移动// i--;// 删除成功后,必须退一步,这样可以保证下次回到这个位置,如此则不会跳过数据// }// } //[98, 77, 66, 89, 79, 50, 100]原集合// System.out.println(scores); //[98, 89, 100] // 执行第二个方案之前要将上面的方案注释,因为没有如果执行了上面的代码,集合的元素已经发生变化,不是原来的集合元素 // 完美方案二: 倒着遍历,这样集合元素的索引不会发生变化,因为后面的元素已经扫描过了,向前移动也没事// [98, 77, 66, 89, 79, 50, 100] for (int i = scores.size() - 1 ; i >= 0 ; i-- ) { // 倒着遍历的初始值是最后一个元素,判断条件是大于等于第一个元素索引 int score = scores.get(i); if (score >= 80){ scores.remove(i); } } System.out.println(scores); }}