java - Remove entries from the list using iterator -
java - Remove entries from the list using iterator -
i need write simple function delete entries in list
contains objects of class elem
. wrote function removeallelements
, not work if size of list<elem>
greater 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(); // not work 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; } }
edit#1 error message following:
exception in thread "awt-eventqueue-0" java.util.concurrentmodificationexception @ java.util.abstractlist$itr.checkforcomodification(unknown source) @ java.util.abstractlist$itr.next(unknown source)
the code doesn't compile. this.tokens
?
anyway, if want remove element while iterating, must using iterator's remove method:
itr.next(); itr.remove();
your removeallelements
method this.elements.clear()
, though. much more straightforward , efficient.
java list arraylist
Comments
Post a Comment