使用 For 循环从 ArrayList 中删除数据 [英] Delete data from ArrayList with a For-loop

查看:33
本文介绍了使用 For 循环从 ArrayList 中删除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的问题.我以为这会花费我几分钟,但我现在挣扎了几个小时......这是我得到的:

I got a weird problem. I thought this would cost me few minutes, but I am struggling for few hours now... Here is what I got:

for (int i = 0; i < size; i++){
    if (data.get(i).getCaption().contains("_Hardi")){
        data.remove(i);
    }
}

dataArrayList.在 ArrayList 中,我得到了一些字符串(总共 14 个左右),其中 9 个字符串的名称是 _Hardi.

The data is the ArrayList. In the ArrayList I got some strings (total 14 or so), and 9 of them, got the name _Hardi in it.

使用上面的代码,我想删除它们.如果我 replace data.remove(i);System.out.println 那么它会打印 9 次,这很好,因为 _Hardi 在 ArrayList 9次.

And with the code above I want to remove them. If I replace data.remove(i); with a System.out.println then it prints out something 9 times, what is good, because _Hardi is in the ArrayList 9 times.

但是当我使用 data.remove(i); 时,它不会删除所有 9 个,而只是删除了几个.我做了一些测试,我也看到了这个:

But when I use data.remove(i); then it doesn't remove all 9, but only a few. I did some tests and I also saw this:

当我将字符串重命名为:哈迪1哈迪2哈迪3哈迪4哈迪5哈迪6

When I rename the Strings to: Hardi1 Hardi2 Hardi3 Hardi4 Hardi5 Hardi6

然后它只删除偶数(1、3、5 等).他总是跳过 1,但不知道为什么.

Then it removes only the on-even numbers (1, 3, 5 and so on). He is skipping 1 all the time, but can't figure out why.

如何解决这个问题?或者也许是另一种删除它们的方法?

How to fix this? Or maybe another way to remove them?

推荐答案

这里的问题是您正在从 0 到 size 进行迭代,并且在循环内您正在删除项目.删除项目会减小列表的大小,当您尝试访问大于有效大小(删除项目后的大小)的索引时,列表将失败.

The Problem here is you are iterating from 0 to size and inside the loop you are deleting items. Deleting the items will reduce the size of the list which will fail when you try to access the indexes which are greater than the effective size(the size after the deleted items).

有两种方法可以做到这一点.

如果不想处理索引,请删除使用迭代器.

Delete using iterator if you do not want to deal with index.

for (Iterator<Object> it = data.iterator(); it.hasNext();) {
if (it.next().getCaption().contains("_Hardi")) {
    it.remove();
}
}

否则,从末尾删除.

for (int i = size-1; i >= 0; i--){
    if (data.get(i).getCaption().contains("_Hardi")){
            data.remove(i);
    }
 }

这篇关于使用 For 循环从 ArrayList 中删除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆