-3

I am working with below code :

List<String> layerDataList = new ArrayList<String>();
if (layerDataList.isEmpty()) {
  layerDataList.add(layerData);
}

Iterator<String> lir = layerDataList.iterator(); // Iterator created

while (lir.hasNext()) {
  String layerD = lir.next();
  if (layerD != layerData) {
    layerDataList.add(layerData);
  }
}

I got exception : java.util.ArrayList$Itr.checkForComodification(Unknown Source)

What is the issue?

Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94
  • Also, let's just throw in [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) for good measure. – Andy Turner Feb 05 '16 at 09:58
  • 1
    you have to use methods on `Iterator` and `ListIterator` to add and remove elements from list, don't do it directly on `List` itself. [See question](http://stackoverflow.com/questions/223918/iterating-through-a-list-avoiding-concurrentmodificationexception-when-removing) – Sabir Khan Feb 05 '16 at 10:05
  • read about Fail-Safe and Fail-Fast in collection. It's great if you will google it. – Musaddique S Feb 05 '16 at 10:31
  • Why are you asking the same question again? Do you assume that the correct answer will change? – Hovercraft Full Of Eels Feb 07 '16 at 05:46

3 Answers3

3

You can't traverse through the list using Iterator and modify the list with List-level add/remove methods at the same time.

To add an element in such situations you can use ListIterator and its method add.

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
1

Whenever you modify a Collection, you invalidate all the Iterators that depend on it. Instead, you could use the iterator itself (assuming you define it as a ListIterator, or something down those lines) to modify the collection:

ListIterator<String> lir = layerDataList.iterator();
while (lir.hasNext()) {
  String layerD = lir.next();
  if (layerD != layerData) {
    lir.add(layerData); // Here!
  }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

The documentation says:

The iterators returned by this ArrayList'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. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

To add while iterating to a list you can try like this:

ListIterator<String> lir = layerDataList.iterator();
while (lir.hasNext()) {
  String layerD = lir.next();
  if (layerD != layerData) {
    lir.add(layerData); 
  }
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331