使用迭代器从列表中删除条目
我需要编写一个简单的函数来删除List
中包含Elem
类对象的所有条目。 我写了函数removeAllElements
,但是如果List
的大小大于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 elements = new ArrayList(); 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
?
无论如何,如果你想在迭代时删除一个元素,你必须使用迭代器的remove方法来做它:
itr.next(); itr.remove();
但是,你的removeAllElements
方法可以执行this.elements.clear()
。 更直接,更有效率。
在迭代时删除元素时,必须使用itr.remove()
而不是this.tokens.remove(e)
。
有关更多详细信息,请查看Iterator.remove()
我假设tokens
是你的Arraylist?
从数组列表中动态删除元素时,需要使用迭代器提供的.remove方法。 所以你需要做这样的事情:
public void removeAllElements() { Iterator itr = this.elements.iterator(); while(itr.hasNext()) { Object e = itr.next(); itr.remove(); } }
如果您只想从列表中删除所有元素,可以调用Arraylist的.clear方法:
从此列表中删除所有元素。 此调用返回后,列表将为空。
您必须调用迭代器的“删除”方法: http : //www.java-examples.com/remove-element-collection-using-java-iterator-example 。