0

I'm trying to transfer the contents of an ArrayList from one Book object to the other Book object. The method would be called as

bookA.transfer(bookB);

However, with the code below, I get an error that says "java.util.ConcurrentModificationException" and shows the problem at the line "for(String page: pages) {". Both objects have an ArrayList called pages, and I'm not sure that it's differentiating between the two different lists when I use one as "pages.get(...)" which is the object the method is called on and "other.pages.get(...)" which is the object that is being passed as a parameter to transfer its contents. Is this the correct way of doing this? Or did I go wrong somewhere else?

 public class Book {
 ArrayList<String> pages;

 public Book ()
 {
pages = new ArrayList<String>();
 }  

 public void transfer(Book other) {
     int i = 0;
     for(String page: pages) {
         String temp = other.pages.get(i);
         pages.add(temp);
         other.pages.remove(i);
         i++;
     }
     System.out.println("Book" + pages);
     System.out.println("Book" + other.pages);
 }

*The other question was about using an iterator class which i am not.

John Kerry
  • 45
  • 6

1 Answers1

2

You cannot modify collection that you currently iterating on:

 for(String page: **pages**) {
     String temp = other.pages.get(i);
     **pages.add(temp);**
     other.pages.remove(i);
     i++;
 }

Not sure what the logic behind your code, but why not just call it like:

 pages.addAll(other.pages);
 other.pages.clear();
wikisky
  • 345
  • 2
  • 13
  • Thanks this worked. I realized that I was iterating through the wrong ArrayList, should have been other.pages and not pages – John Kerry Sep 28 '18 at 22:12
  • You should accept this answer if it worked for you and give @wikisky the credit he deserves :D – ctj232 Sep 28 '18 at 22:14