0

Why i am getting this exception?

I am new to java and stackoverflow

ArrayList<A> a = new ArrayList<A>();
ArrayList<B> b = new ArrayList<B>();

a.add(new A("A"));
a.add(new A("B"));
a.add(new A("C"));

b.add(new B(new A("A"), "a"));
b.add(new B(new A("B"), "b"));
b.add(new B(new A("C"), "c"));

System.out.println(a);
System.out.println(b);

bIterator = b.iterator();
while(bIterator.hasNext()) {
    b.add(new B(bIterator.next(), "a"));
}

error

Exception in thread "main" java.util.ConcurrentModificationException
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
  • Your first port of call should *always* be [the documentation](http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html): *"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**. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly..."* *(my emphasis)* – T.J. Crowder Jul 16 '15 at 11:27

4 Answers4

5

You get this exception because you iterate over a list and modify it at the same time.

Jens
  • 67,715
  • 15
  • 98
  • 113
1

Below piece of code is creating problem, because you are iterating over a list and modifying it at the same time.

while(bIterator.hasNext()) {
    b.add(new B(bIterator.next(), "a"));
}

ConcurrentModificationException

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
0
while(bIterator.hasNext()) {
    b.add(new B(bIterator.next(), "a"));
}

If you see carefully above lines, you are iterating over that list and trying to add some more elements at same time.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

The exception is thrown because you are modifying an ArrayList when iterating it. However, there are List implementations that support this, such as CopyOnWriteArrayList.

cypher
  • 6,822
  • 4
  • 31
  • 48