java--容器---ArrayList的删除

ArrayList是经常使用的容器,在删除元素的时候经常出错

import java.util.ArrayList;
public class Test2 {

    public static void main(String[] args) {
        String str = "abc";
        ArrayList<String> aList = new ArrayList<String>();
        aList.add("abc");
        aList.add("abc");
        aList.add("abc");
        aList.add("a1bc");
        aList.add("a2bc");
        aList.add("abc");
        aList.add("a3bc");
        aList.add("abc");
        aList.add("abc");

        for (String a : aList) {
            System.out.println("元素:::" + a);
        }
        remove1(aList);
        System.out.println("删除之后。。。。。");
        for (String a : aList) {
            System.out.println("元素" + a);
        }

错误例子一:

public static void remove1(ArrayList<String> list) {
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            if (s.equals("abc")) {
                list.remove(s);
            }
        }
    }

运行结果:
元素a1bc
元素a2bc
元素a3bc
元素abc
元素abc
发现里面有“abc”是没有删除的。
来分析一下原因和解决办法:查找源码Object的remove()发现:

public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

查看fastRemove()的源码

private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,numMoved);
        elementData[--size] = null; // Let gc do its work
    }

里面有个system.arraycopy方法,导致删除元素时涉及到数组元素的移动。针对错误写法一,在遍历第一个字符串acb时因为符合删除条件,所以将该元素从数组中删除,并且将后一个元素移动(也就是第二个字符串abc)至当前位置,导致下一次循环遍历时后一个字符串abc并没有遍历到,所以无法删除。
针对第一种方法的话,可以这样子解决:

public static void remove1(ArrayList<String> list) {
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            if (s.equals("abc")) {
                list.remove(s);
                i--;//把元素下标--;
            }
        }
    }

也可以使用倒序删除方法:


public static void remove(ArrayList<String> list)
{
for (int i = list.size() - 1; i >= 0; i--)
{
String s = list.get(i);
if (s.equals("abc"))
{
list.remove(s);
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值