删除ArrayList中的数据与一个for循环 [英] Delete data from ArrayList with a For-loop

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

问题描述

我有一个奇怪的问题。 我认为这会花了我几分钟的时间,但现在我struggeling了几个小时...... 下面是我得到了什么:

I got a weird problem. I thought this would cost me few minutes, but I am struggeling 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);
        }
}

数据的ArrayList 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.

和与code以上我想删除它们。 如果我更换data.remove(我); 的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(我); 那么它不会删除所有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:

当我重新命名的字符串来: Hardi1 Hardi2 Hardi3 Hardi4 Hardi5 Hardi6

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.

是否有人知道如何解决这个问题?或者,也许另一种方式将其删除?

Does someone know how to fix this? Or maybe another way to remove them?

感谢不已, Bigflow

Thanks already, Bigflow

推荐答案

这里的问题是,你是从0迭代的尺寸和内循环要删除项。删除的项目会降低列表的大小时试图访问它们是大于有效尺寸(已删除项目后的大小)的索引,这将失败。

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);
    }
 }

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

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