0

Sorry about title. I'm trying to write a program that replaces the elements from an array A with elements from an array B of the same size, while also removing those elements from array B. Nothing fancy, just testing things out before my exam.

I tried doing so with nested for-loops, the first being the "traditional for-loop" and the second being the "enhanced for-loop", but for some reason instead of replacing element 0 from array A with element 0 from array B, it's replacing all elements from array A with element 2 from array B. And when trying to remove the elements, it gives me an error. Any idea why this is happening?

Output included in code block because stackoverflow just would not let me post if it wasn't.

And line 30 is "for(String s : list2)". I took out the header.

public class Test {
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<>();
        list1.add("one");
        list1.add("two");
        list1.add("three");

        List<String> list2 = new ArrayList<>();
        list2.add("four");
        list2.add("five");
        list2.add("six");

        System.out.println(list1);
        System.out.println(list2);

        for(int i = 0; i < list1.size(); i++){
            for(String s : list2){
                list1.set(i, s);
                //list2.remove(i);
            }
        }
        System.out.println(list1);
    }
}

The output without the "list2.remove(i)" line:

[one, two, three]
[four, five, six]
[six, six, six]

The output with the "list2.remove(i)" line:

[one, two, three]
[four, five, six]
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
    at java.util.ArrayList$Itr.next(ArrayList.java:859)
    at Test.main(Test.java:30)
C:\Users\izabe\AppData\Local\NetBeans\Cache\10.0\executor- 
snippets\run.xml:111: The following error occurred while executing this 
line:
C:\Users\izabe\AppData\Local\NetBeans\Cache\10.0\executor- 
snippets\run.xml:94: Java returned: 1
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42

3 Answers3

2

You are very much overcomplicating things. You are doing things "manually" that are already implemented by the classes you are using!

The real answer here is to step back and study the interface that the Collection, or more appropriately here, the List interface offer to you.

What you find there are calls like:

  • clear(): to remove all elements currently stored in a Collection
  • addAll(): to add all elements of another Collection to another one

Also note that your exception is almost self-explanatory, and beyond that, has been asked and answered here many many times, see here for example. The real answer here is again: to not ask for explanations, but to be curious, and to use a search engine.

You learn programming by conquering the world yourself, not by asking others for explanations.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

The reason behind it is replacing all elements of Array with same is that you are not moving pointer of first Array to whom you are replacing.

Working version of your code might look like

//assuming both array have same length
for(int i = 0; i < list1.size() && list1.size() <= list2.size(); i++){
          list1.set(i, list2.get(i));

}

Second, you are getting concurrent modification exception is that you are reading and removing(writing in sense) the array at same time. (mod flag is not reseted). For this better is to use Iterator<>

Improved code will look like

//assuming both array have same length
int i = 0;
Iterator<String> iterator = list2.iterator();
while(iterator.hasNext() && i < list1.size()) {
    list1.set(i, iterator.next());
    i++;
    iterator.remove();   
}
Oomph Fortuity
  • 5,710
  • 10
  • 44
  • 89
0

Yes. You could also do:

    list1.clear();
    for(String s : list2){
        list1.add(s);
    }
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24