0

I have the following code:

// Creates ArrayList with integers 0-9
ArrayList<Integer> intKeys = new ArrayList<Integer>();
for (int x = 0; x < 10; x++) {
    intKeys.add(x);
}

// Creates iterator with integers 0-9
Iterator<Integer> allKeys = intKeys.iterator();

// Loops 10 times, each time obtaining a key to remove from the ArrayList
for (int x = 0; x < 10; x++) {
    Integer key = allKeys.next();
    intKeys.remove(key);
}

I understand that ConcurrentModificationException is thrown if an element of a collection is removed while the collection is being looped over, such as:

for (String key : someCollection) {
    someCollection.remove(key);    
}

but right now I'm looping over nothing - just an arbitrary number of times. Furthermore, the error line is interestingly Integer key = allKeys.next(); What could be the cause of this exception?

sle
  • 165
  • 1
  • 1
  • 8
  • 1
    "but right now I'm looping over nothing" you are looping over `intKeys` list by `allKeys.next();` but you are also modifying that list in next step via `intKeys.remove(key);`. Don't you think that this can affect `Iterator allKeys` (which assumes that array will not be modified by anyone else while it is looping over it)? – Pshemo Oct 03 '17 at 19:12
  • 1
    "as I am not looping through a collection" what do you think `allKeys.next();` does? `allKeys` is an Iterator. If you want to remove element which it returned, then use `allKeys.remove()` not `intKeys.remove(key);` (where `intKeys` is List). – Pshemo Oct 03 '17 at 19:18
  • @Pshemo Oh, I see. Thanks, that makes sense. – sle Oct 03 '17 at 19:19

1 Answers1

0

You cannot use the list's Iterator object at all when you are removing items while looping.

If you are removing all the items from the list:

while (!list.isEmpty()) {
    Integer i = list.remove(0);
    //Do something with the item
}

Otherwise, you can iterate without the iterator:

for (int i = 0; i < list.length(); i++) {
    //Do something with the list
}
cdbbnny
  • 330
  • 2
  • 9