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

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

问题描述

我有一个 ArrayList 假设 list,它有 8 个项目 AH,现在我想从 <代码>列表我该怎么做.

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天全站免登陆