foreach Java syntax hides the iterator, but hiding it makes it impossible to call the remove method on this.
So, I would do:
ArrayList<Integer> list = new ArrayList<Integer>(); // add some values to it int count = 0; for(Iterator<Integer> it = list.iterator();it.hasNext();count++){ //increments count++ Integer currentInt = it.next(); if(currentInt % count == 0){ it.remove(); } }
You can see that the same function is achieved without the need for a secondary iterator.
You cannot iterate over the same list at the same time. To summarize, the modcount variable modcount used to detect an unexpected change in itself each time the list changes or repeats in parallel. Thus leading to a ConcurrentModificationException . It appears very often with a multi-threaded environment, and developers should be aware of this.
Also, prefer to use a for loop instead of a while to iterate through the collection.
Why?
Because with the while method, you allow the iterator object to remain in scope after the loop, whereas with for it is not. A simple it.next() callback would end with a NoSuchElementException .
Best stored;)
source share