Reputation: 1409
I'm trying to remove an item of type SubClass from an ArrayList using a foreach, and removing it right when it finds it.
The code:
for (SuperClass item : list)
{
if (item instanceof SubClass)
{
list.remove(item);
}
}
I don't really know how the Iterator works in this case, but what I'm asking is: is this safe? Or should it throw an out of bounds exception?
Any help is appreciated!
Upvotes: 0
Views: 155
Reputation: 774
As sanbhat say it is not safe. but what you want to do can be solve by 2 diffenret way.
1) you can store all the objects & after foreach loop you can remove by index. but it is not good way.
2) use for loop (not foreach loop) & ittrate till length. then if object found remove it. thats it.
(make sure you have written condition like i
Upvotes: 0
Reputation: 17622
You cant remove items from a list
while using foreach statement. You will get ConcurrentModificationException
You need to use Iterator.remove()
method
for(Iterator<SuperClass> i = list.iterator(); i.hasNext(); ) {
SuperClass s = i.next();
if(s instanceof SubClass) {
i.remove();
}
}
Upvotes: 7
Reputation: 8466
Try ListIterator:
List<SuperClass> sampleList = new ArrayList<SuperClass>();
ListIterator<SuperClass> listIterator = sampleList.listIterator();
//
listIterator.remove();
//
Upvotes: 0