How to add values to a list while iterating it

Deepak Ramakrishnan Kalidass picture Deepak Ramakrishnan Kalidass · May 15, 2014 · Viewed 14k times · Source

I Have a scenario such like this

List<String> xxx = new ArrayList
for(String yyy : xxx){
   for(String zzz:xyxy){
     if(!zzz.equals(yyy)){
       xxx.add(zzz);
     }
   }
}

But i get java.util.ConcurrentModificationException: null exception.Can anyone help me solve this issue.? Can anyone give me alternate method to perform this ?

Answer

awksp picture awksp · May 15, 2014

Looking at the ArrayList API:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

So you're going to need to explicitly get a ListIterator and use that to properly alter your ArrayList. Also, I don't believe you can use a for-each loop because the iterators in those are separate from your explicitly retrieved iterator. I think you'll have to use a while loop:

List<String> xxx = new ArrayList<>();
ListIterator<String> iterator = xxx.listIterator();
while (iterator.hasNext()) {
    String s = iterator.next();
    for (String zzz : xyxy) {
        if (!zzz.equals(s)) {
            iterator.add(zzz); //<-- Adding is done through the iterator
        }
    }
}