ArrayList 集合元素的正确删除

一.代码

import java.util.ArrayList;

public class ArrayListTest3 {
    public static void main(String[] args) {
        // 目标:学习遍历并删除元素的正确方法

        // 1. 定义一个ArrayList 集合存储一个班学生成绩。 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);

        //[98, 77, 66, 89, 79, 50, 100]
        //[98, 66, 89, 50, 100]


        // 错误删除 会漏掉元素
        for (int i = 0; i < scores.size(); i++) {
            if (scores.get(i) < 80) {
                scores.remove(i);
            }
        }
        System.out.println(scores);

        // 方案一:
        for (int i = 0; i < scores.size(); i++) {
            if (scores.get(i) < 80) {
                scores.remove(i);
                i--; //删除之后退一步 保证下次回到这个位置 不会漏掉数据
            }
        }
            System.out.println(scores);
        // 方案二:从后倒着遍历
        for (int i = scores.size()-1; i >= 0; i--) {
            if (scores.get(i) < 80) {
                scores.remove(i);
            }
        }
        System.out.println(scores);
    }
}

二.运行结果

565b0b0adbda4ad4917606b91d0a51b9.png

三.注意

错误删除 中 :  如果出现连着两个低于80分的  删掉一个 是后面的元素往前走 但i往后加1  就会有第二个被漏掉 

方案一 在其中加一个 i--就会避免这种情况

方案二 倒着遍历  如果出现连着两个低于80分的 删掉以后 是后面已经遍历过的往前走  i往前减1 不会漏掉

 

 

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值