从ArrayList中删除项目 [英] Remove Item from ArrayList

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

问题描述

我有一个的ArrayList 假设列表,它有8个项目啊,现在我想删除1,从列表存储在int数组3,5位项目我怎么能做到这一点。

I have an ArrayList suppose list, and it has 8 items A-H and now I want to delete 1,3,5 position Item stored in int array from the list how can I do this.

我试图用做

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");

int i[] = {1,3,5};

for (int j = 0; j < i.length; j++) {
    list.remove(i[j]);
}

但经过第一项删除阵列定位的改变,并在接下来的迭代它删除错误的元素或给予例外。

But after first item deleted positioned of array is changed and in the next iterate it deletes wrong element or give exception.

推荐答案

在这种特殊情况下的,应删除降序排列的元素。一是指数 5 ,然后 3 ,然后 1 。这会从列表中删除的元素没有不良的副作用。

In this specific case, you should remove the elements in descending order. First index 5, then 3, then 1. This will remove the elements from the list without undesirable side effects.

for (int j = i.length-1; j >= 0; j--) {
    list.remove(i[j]);
}

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

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