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

查看:40
本文介绍了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.

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

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 时,它们是多功能的,比 数组.您可以通过删除整个索引来缩短数组,为其添加索引,并使用 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天全站免登陆