Re: Removing object from arraylist when pointed to by iterator
softwarepearls_com <info@softwarepearls.com> wrote in news:f472d0ee-f85b-
4da3-ad91-90e2ab4524ce@r66g2000hsg.googlegroups.com:
On Aug 24, 3:00?am, "nooneinparticular314...@yahoo.com"
<nooneinparticular314...@yahoo.com> wrote:
I have an arraylist of objects of a certain type. ?I use an iterator
on that arraylist to get the next instance of the object, using the
iterator.next() method. ?But if I succeed in performing an operation
on the object, I want to remove the object from my arraylist. ?The
question is how I remove it without calling .next() again, since that
will remove the next one, not the current one? ?ie. ?If I am currentl
y
working on the object at position 4 in the arraylist (through the
iterator), I want to remove the object at position 4. ?But I don't
know what position the object is in because I got it through the
iterator.
I would say you're caught in the iterator "routine" so many fall prey
to... you should not be using an iterator when working with an
ArrayList ! You should be iterating the "old fashioned" way ... using
direct get(int) .. these don't entertain the concept of
ConcurrentModificationException. It's faster too.
If one wants to iterate thru the ArrayList, and remove items here and
there, I'd say an Iterator is much simpler and safer to use.
Iterating with an index may cause undesired results, as shown by the
following example.
package itertest;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class Main
{
public static void main(String[] args)
{
final int SIZE=1000;
List list = new ArrayList(SIZE) ;
for (int i=0; i < SIZE; i++)
{
list.add(Integer.toString(i));
}
for (int i=0; i < list.size(); i++)
{
String s = (String) list.get(i) ;
System.out.println("list.get(" + i + ") (list.size=" +
list.size() + ") = " + s) ;
list.remove(i) ;
}
list = new ArrayList(SIZE) ;
for (int i=0; i < SIZE; i++)
{
list.add(Integer.toString(i));
}
for (Iterator i=list.iterator(); i.hasNext(); )
{
String s = (String) i.next() ;
System.out.println("i.next() = " + s) ;
i.remove();
}
}
}
The list will never get iterated thru by using get() ! The algorighm
using that requires something more, which makes it more complicated.