-2

I want to print elements of two arraylists with using two while conditions. But I get Concurrent Modification exception when trying to implement that.

What have I done wrong?

public void Insert_Answers(Enumeration<String> ques, Enumeration<String> ans){

    try {

        while(ans.hasMoreElements()){
            String answer = ans.nextElement();

            System.out.println(answer);

           while(ques.hasMoreElements()){

               String question = ques.nextElement();
               System.out.println(question);

         }
        }
    } 
     catch (Exception ex) {
        Logger.getLogger(DbInsert.class.getName()).log(Level.SEVERE, null, ex);
    }
}

This is the Test.java class where main method is contained

public class Test {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    DbInsert dbIns = new DbInsert();

    ArrayList<String> arr1 = new ArrayList<String>();
    arr1.add("a");
    arr1.add("b");
    arr1.add("c");
    arr1.add("d");
    Enumeration earr1 = Collections.enumeration(arr1);

    ArrayList<String> arr2 = new ArrayList<String>();
    arr2.add("e");
    arr1.add("f");
    arr1.add("g");
    arr1.add("h");
    Enumeration earr2 = Collections.enumeration(arr2);

    dbIns.Insert_Answers(earr1, earr2);
}

}
Marcel Gosselin
  • 4,610
  • 2
  • 31
  • 54
userAlma
  • 49
  • 6

1 Answers1

6

My guess is you made a typo when populating arr2

arr2.add("e");
arr1.add("f");
arr1.add("g");
arr1.add("h");

you probably meant those adds to be to arr2

arr2.add("e");
arr2.add("f");
arr2.add("g");
arr2.add("h");

The concurrent modification error happens because you are adding to the backing List while the iteration is in progress.

I'm also not sure why you are using Enumeration. You should use Iterator instead.

Iterator<String> arr1Iter = arr1.iterator();

See this other SO question for why you should use Iterator instead : Difference between Java Enumeration and Iterator

Community
  • 1
  • 1
dkatzel
  • 31,188
  • 3
  • 63
  • 67
  • That was it :D Thanks for pointing out that.I am not much familiar with all this but just wanted to test whether this way is working with arraylist. will use an Iterator for implementation. Thanks again for the advice :) – userAlma Jan 01 '15 at 06:31