Java Arraylist通过索引删除多个元素 [英] Java Arraylist remove multiple element by index

查看:1120
本文介绍了Java Arraylist通过索引删除多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

for (int i = 0; i < myarraylist.size(); i++) {
        for (int j = 0; j < stopwords.size(); j++) {
            if (stopwords.get(j).equals(myarraylist.get(i))) {
                myarraylist.remove(i);
                id.remove(i);
                i--; // to look at the same index again!
            }
        }
    }

我有问题..删除元素后,所有索引始终更改,上面的循环如此混乱.

I have problem.. after element removed, all index always changed, the loop above so messy.

为说明: 我有54​​个数据,但是删除元素后,上面的循环变得混乱了.所以只检查了50个数据.

To illustrate: I have 54 data, but loop above become messy after element removed.. so only 50 data that checked.

还有其他方法或修复我的代码以按索引删除多个元素吗? 元素索引对我来说非常重要,要删除另一个具有相同索引的arraylist.

Is there another way or fix my code to remove multiple element by index?? element index is so important to me, to remove another arraylist that have the same index.

推荐答案

您需要记住的一件事是,当您使用ArrayLists时,它们比Arrays用途更广泛.您可以通过删除整个索引来缩短数组,为它添加索引,并使用ArrayLists做一些奇妙的事情.

One thing you need to keep in mind is that when you use ArrayLists that they are meant to be versatile, moreso than Arrays. You can shorten an array by removing an entire index, add an index to it, and do wonderfulness with ArrayLists.

对于那些没有意识到或记住的人来说,这是一个普遍的问题,当您删除一个值时,ArrayList索引(或任何正确的复数是)会重新调整,而ArrayList会缩短.

This is a common problem with people who do not realize, or remember, that when you remove a value, the ArrayList indexes (or whatever the correct plural is) readjust and the ArrayList shortens.

尝试从ArrayList中删除元素时,应始终从ArrayList的末尾开始.

When attempting to remove elements from an ArrayList, you should always start at the end of the ArrayList.

for(int x = arrayList.size() - 1; x > 0; x--)
{
    arrayList.remove(x);
}

这应该为您提供所需的功能.查看其他的 ArrayList API 可能对您有帮助的方法.

This should provide you with the function that you are looking for. Take a look at the ArrayList API for other methods that may help you.

这篇关于Java Arraylist通过索引删除多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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