我在循环中从arraylist中删除东西。我注意到,当我连续两件事需要拆除时,它会错过第二件。 例如,我的代码检查arraylist中的数字是否小于静态数字。我有:
arraylist[2,5,15,30]
我正在检查
check = 10
所以我有一个循环
for (int i=0;i<arraylist.size();i++){
if(check > arraylist.get(i){
arraylist.remove(i);
}
}
我很确定我错过了第二个,因为我的arraylist最初编号是这样的:
0,1,2, 3
arraylist[2,5,15,30]
删除第一个条目后,将其更改为:
0,1, 2
arraylist[5,15,30]
我已经检查过0,所以我不需要再检查一下。 有一个简单的方法来解决这个问题吗?不改变我的数据结构? 感谢
答案 0 :(得分:4)
使用迭代器或向后循环遍历ArrayList。
答案 1 :(得分:1)
答案 2 :(得分:1)
使用Iterator
for (Iterator<Integer> it = list.iterator(); it.hasNext();) {
if (check > it.next()) {
it.remove();
}
}
答案 3 :(得分:1)
每次从ArrayList中删除项目时,您都可以减去i
,如下所示:
for (int i=0;i<arraylist.size();i++){
if(check > arraylist.get(i){
arraylist.remove(i);
i = i--;
}
}
答案 4 :(得分:1)
您可以使用Iterator或ListIterator。这些接口让你可以一步一步地迭代和删除集合。
样品测试:
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class ListIteratorTest {
List<Integer> list;
@Before
public void setUp() {
list = new ArrayList<>();
list.add(2);
list.add(5);
list.add(15);
list.add(30);
}
@Test
public void testListIterator() {
ListIterator<Integer> lit = list.listIterator();
while(lit.hasNext()){
int val = lit.next();
if(val > 10){
lit.remove();
}
}
assertFalse(list.contains(15));
}
}
答案 5 :(得分:0)
有三种方法可以做到这一点。
使用Iterator&lt;&gt; - 它上面有一个remove()函数,它允许你删除当前项目,迭代器将跟踪tihngs。
从列表末尾开始并向后迭代。
当您移除该项目时,移动当前索引1。
如果要删除大量项目,所有这些情况都会非常低效,因为每次删除一个项目时都会拖拽整个列表。更好的做法是:
// Scan through the array keeping a "read" pointer and a "write" pointer.
int write = 0;
for (int scan=0;scan<arrayList.size();scan++) {
Integer i arrayList.get(scan);
// Only copy items that match the check
if (check <= i) {
if (scan != write) {
arrayList.set(write, i);
}
write++;
}
}
// Remove any "dead" entries from the end of the list
while (arrayList.size() > write) {
arrayList.remove(arrayList.size()-1);
}
否则,对于每个元素,在删除之后,每个元素都会被移除。使用此代码,无论需要移动多少个点,每个元素都只会被拖拽一次。