问题描述
我需要编写一个简单的函数来删除 List
中包含 Elem
类的对象的所有条目.我写了removeAllElements
这个函数,但是如果List
的大小大于1就不行了.
I need to write a simple function that will delete all entries in the List
that contains objects of the class Elem
. I wrote the function removeAllElements
, but it does not work if the size of the List<Elem>
is greater than 1.
public class Test {
public static void main(String[] args) {
Work w = new Work();
w.addElement(new Elem("a",new Integer[]{1,2,3}));
w.addElement(new Elem("b",new Integer[]{4,5,6}));
w.removeAllElements(); // It does not work for me.
}
}
public class Work {
private List<Elem> elements = new ArrayList<Elem>();
public void addElement(Elem e) {
this.elements.add(e);
}
public void removeAllElements() {
Iterator itr = this.elements.iterator();
while(itr.hasNext()) {
Object e = itr.next();
this.elements.remove(e);
}
}
}
public class Elem {
private String title;
private Integer[] values;
public Elem(String t,Integer v) {
this.title = t;
this.values = v;
}
}
编辑#1错误信息如下:
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
推荐答案
代码无法编译.什么是this.tokens
?
The code doesn't compile. What is this.tokens
?
无论如何,如果你想在迭代时移除一个元素,你必须使用迭代器的remove方法来完成:
Anyway, if you want to remove an element while iterating, you must do it using the iterator's remove method:
itr.next();
itr.remove();
不过,您的 removeAllElements
方法可以只执行 this.elements.clear()
.更加直接和高效.
Your removeAllElements
method could just do this.elements.clear()
, though. Much more straightforward and efficient.
这篇关于使用迭代器从列表中删除条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!