Reputation: 576
I'm trying delete strings which have even index numbers in this ArrayList, using "Iterator".remove.
import java.util.*;
import static java.lang.System.out;
class MAIN
{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
Iterator i = al.iterator();
int len;
Scanner sc = new Scanner(System.in);
out.printf("Size:");
len = sc.nextInt();
while( len!=0 )
{
al.add( sc.next() );
len -= 1;
}
Object o;
for( len = 0 ; len < al.size() ; len +=1)
{
out.println(al);
if( len%2==0 )
{
o = i.next();
out.println(o);
i.remove();
i.next();
}
}
return;
}
}
I'm getting the "ConcurrentModificationException" at i.next();. What's wrong ?
Upvotes: 0
Views: 133
Reputation: 878
Use an Iterator and then call remove() over it:
Iterator<String> itr = list.iterator();
while (itr.hasNext()) {
String s = itr.next();
if (Condition)
itr.remove();
}
Upvotes: 0
Reputation: 80
You are getting error because iterator checks for the modification, check for its implementation which is present in AbstractList class where an int variable modCount is defined that provides the number of times list size has been changed.
Check this link for detailed answer:
http://www.javacodegeeks.com/2011/05/avoid-concurrentmodificationexception.html
Upvotes: 0
Reputation: 285430
You're not using the iterator to iterate through your correction, and so you cannot use it to remove elements. To use it correctly, you must loop with the iterator itself.
i.e.,
for (Iterator<E> iter = list.iterator(); iter.hasNext(); ) {
E element = iter.next();
// 1 - can call methods of element
// 2 - can use iter.remove() to remove the current element from the list
// ...
}
Maybe something like:
int count = 0;
for (Iterator<String> iter = al.iterator(); iter.hasNext(); ) {
String element = iter.next();
System.out.print(element);
if (count % 2 == 0) {
iter.remove();
System.out.print(" -- has been deleted");
}
System.out.println();
count++;
}
Another option is to use a for loop to loop backwards through your collection. This can work since removing an item will not change the ordering or indexing of the items before the removed item.
Upvotes: 5