-3

I know there is a lot of question related to this exception. Even I also asked this question before Getting ConcurrentException when working with list and solution was use ListIterator instead of iterator. In my below program I have used ListIterator but still I got this exception.

I am really not able to understand why I got this exception. Can any one help me to sort this out?

  public static void main(String args[]) {
    List<String> myList = new ArrayList<String>();
    myList.add("1");
    myList.add("2");
    myList.add("3");
    myList.add("4");
    myList.add("5");

    List<String> myList_1 = new ArrayList<String>();
    myList_1.add("4");
    myList_1.add("6");


    ListIterator<String> it = myList.listIterator();

    mainLoop:
      while(it.hasNext()) {
        String internalAperture = it.next();
        System.out.println("Aperture:"+internalAperture);
        String refreneceNumber = internalAperture;
        if (refreneceNumber.equals("6")) {

          myList.add("6");
          break;
        }
        else {
          ListIterator<String> it_ = myList_1.listIterator();
          while(it_.hasNext()) {
            String a = it_.next();         
            myList.add(a);
            continue mainLoop;
          }
        }
      }
  }
Community
  • 1
  • 1
Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94
  • 4
    I don't think you understand what a `ListIterator` is. You should not have `myList.add("6");`. [Let the `ListIterator` do that](https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#add-E-)! – Tunaki Feb 07 '16 at 12:07

2 Answers2

0

You get the exception because you modify the list while iterating over it.

The only way the iterator allows you do that is to modify the list through the iterator.

ListIterator only allows to add an element right after its current position. You cannot add to the end of the list. I don't know if that is a problem for your algorithm. If you must add to the end, consider using a for (int i=0; i<list.size(); i++) loop instead (which gives you more control).

Thilo
  • 257,207
  • 101
  • 511
  • 656
0

If you want modify a list while traversing it you can use CopyOnWriteArrayList instead of List:

CopyOnWriteArrayList<String> myList = new CopyOnWriteArrayList<String>();

In other case you can forget about iterator and use usual loop:

for (int i = 0; i < myList.size(); i++) {                
  String internalAperture = myList.get(i);
  //do something
}
Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94
Filomat
  • 753
  • 1
  • 11
  • 16
  • 1
    Hmm. With `CopyOnWriteArrayList` the additions to the list will not be picked up by the iterator. It will continue to loop just over the original list. That may or may not be what the algorithm here needs (not sure). – Thilo Feb 07 '16 at 12:17