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!

1
  • 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() Commented Aug 26, 2013 at 7:04

3 Answers 3

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();
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try ListIterator:

List<SuperClass> sampleList = new ArrayList<SuperClass>();
ListIterator<SuperClass> listIterator = sampleList.listIterator();
//
listIterator.remove();
//

1 Comment

Here 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?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.