package ArrayList; import java.util.ArrayList; /* 遍历并删除元素值 需求: 某个班级的考试在系统上进行,成绩大致为:98, 77, 66, 89, 79, 50, 100 现在需要先把成绩低于80分以下的数据去掉。*/ public class Demo02 { public static void main(String[] args) { // 1、创建集合对象:存入学生成绩(98,77,66,89,79,50,100) 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); /*从后往前推,从前往后推会导致bug, 当删除了i指向的元素时,i+1的元素会迁移,但这个时候i++向后移一位;导致bug*/ for (int i = scores.size() - 1; i >= 0; i--) { int score = scores.get(i); if (score < 80) { scores.remove(i); } } System.out.println(scores); }
java学习案例--遍历并删除元素值
于 2022-06-30 06:22:22 首次发布