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