Re: Modify collection inside iteration
obaqueiro@gmail.com wrote or quoted in
Message-ID: <1163506409.128952.11400@h54g2000cwb.googlegroups.com>:
for (MyObject obj: this.objects) {
if (obj.getFlag()==true){
objects.remove(obj);
}
}
The above code will throw 'ConcurrentModificationException'.
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.
Is there any better way to achieve what I am trying to do?
If 'objects' is linked list (or array list of not large size),
the following code will be good.
<code_1>
Iterator<T> iter = objects.iterator();
while (iter.hasNext()) {
if (...) {
iter.remove();
}
}
</code_1>
But,
If 'objects' is array list of large size, I think that
'code_1' is not good. Because copying internal
array is needed whenever 'iter.remove()' is called.
I think that the following code is better than 'code_1'.
<code_2>
List<T> res = new ArrayList<T>(objects.size());
for (T o : objects) {
if (!(...)) {
res.add(o);
}
}
return res; // replace objects with res
</code_2>