Re: Removing objects from iterating collection
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
obaqueiro@gmail.com schreef:
Hello, I've got a question about the behaviour of Java:
I've got this code:
ArrayList<MyObject> objects = new ArrayList<MyObject>().
... (some code adding objects to array list)...
... some other code...
for (MyObject obj: this.objects) {
if (obj.getFlag()==true){
objects.remove(obj);
}
}
My main concern is what is the behaviour of the for(...) after removing
the obj from the objects list? is this a safe way to proceed? I need to
check all the objects in the list and then remove some of them if
certain condition is true. Usually I make it with for(int
i=0;i<objects.size();i++){...} and then after I remove the object I set
i to 0 (it might be possible just to avoid incrementing the counter).
But I want to know what is the behaivour of the iterator structure [
for(X:Y){} ] in these cases.
It will throw a ConcurrentModificationException, as the Javadoc
http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html would
have told you.
Is there any better way to achieve what I am trying to do?
Yes, explicitly use the (List)Iterator, it has a remove() method. As an
extra bonus, it will be more efficient, since it doesn???t have to do a
lookup for the remove.
for (Iterator iter = objects.iterator(); iter.hasNext();) {
if (iter.next().getFlag()){
iter.remove();
}
}
Note that you do not need the ==true, and you could have chosen a more
expressive name instead of ???flag???.
H.
- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)
iD8DBQFFWbyde+7xMGD3itQRAtrzAJ9EXoXewip9JFVPY9qjZdUk/KPbegCeMHZz
6WSMIIHYGAQuQ+BLv3gHY2M=
=UH1Y
-----END PGP SIGNATURE-----