0

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!

Vlad Ilie
  • 1,389
  • 1
  • 13
  • 37
  • Even if you could do this (and some concurrent lists will allow you) it would be very inefficient i.e. `O(n^2)`. I suggest using your IDE to transform the loop into an Iterator loop and using `Iterator.remove()` – Peter Lawrey Aug 26 '13 at 07:04

3 Answers3

7

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();
     }
}
Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64
0

Try ListIterator:

List<SuperClass> sampleList = new ArrayList<SuperClass>();
ListIterator<SuperClass> listIterator = sampleList.listIterator();
//
listIterator.remove();
//
newuser
  • 8,338
  • 2
  • 25
  • 33
  • [Here](http://docs.oracle.com/javase/6/docs/api/java/util/ListIterator.html) it writes that: `remove() Removes from the list the last element that was returned by next or previous (optional operation).` I suspect that the comment lines represent the lines that should contain the actual foreach statements that use the Iterator? – Vlad Ilie Aug 26 '13 at 07:02
0

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

Pulah Nandha
  • 774
  • 4
  • 23