Re: Best way to loop through ArrayList and remove elements on the
way?
Kevin <happy_singapore@yahoo.com.sg> writes:
for a ArrayList, in single thread mode (only one thread will access
this ArrayList), what is the best way to:
1) loop through all the element of this arraylist (for example, each
item of it is a String).
2) do some check on each item (for example, check if it equals to
"abc").
3) remove this item from the arraylist if the above check is true.
First of all, an ArrayList takes linear time to remove a single
element, so repeated removal is a bad idea.
Either use a LinkedList, which can remove in constant time during
iteration, or first collect the elements in a HashSet and then remove
them at the end using Collection.removeAll(Collection). I suggest the
latter.
For ArrayList, the removeAll method takes time proportional to the
size of the list times the lookup time for the argument collection.
Using a HashSet as argument should minimize the time it takes.
If you only remove a few values, any collection will probably suffice.
I.e., either:
LinkedList tmpLinkedList = new LinkedList(myarraylist);
for(Iterator iter = tmpLinkedList.iterator(); iter.hasNext();) {
if (test(iter.next)) { iter.remove(); }
}
myarraylist.clear();
myarraylist.addAll(tmpLinkedList);
or
HashSet toRemove = new HashSet();
for(Iterator iter = myarraylist.iterator(); iter.hasNext();) {
Object elem = iter.next();
if (test(elem)) { toRemove.add(elem); }
}
myarraylist.removeAll(toRemove);
This is assuming the test is complicated. If it's just equality
check, then you might be able to use removeAll directly.
Is using iterator() and then use iterator.remove() the best way?
For the above reasons, I'd say no.
Like:
for (Iterator it = myarraylist.iterator(); it.hasNext(); )
{
String s = (String) it.next();
if (s.equals("abc"))
{
it.remove();
}
};
In this simple case, where you only compare for equality (and even to
only a single value), it would suffice to do:
myarraylist.removeAll(Collections.singletonSet("abc"));
If you have more values, but still only do equality checks, just create
a collection and remove them all.
/L
--
Lasse Reichstein Nielsen - lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'