CopyOnWriteArrayList iterator behaviour?

package org.example;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListExamples {
public static void main(String[] args) {
List<String> names = new CopyOnWriteArrayList<>(
Arrays.asList("John", "Anton","Heinz")
);
for (Iterator<String> it = names.iterator(); it.hasNext(); ) {
String name = it.next();
System.out.println("Checking: " + name);
if (name.contains("o")) names.remove(name);
}
System.out.println("names = " + names);
}
}
package org.example;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListExamples {
public static void main(String[] args) {
List<String> names = new CopyOnWriteArrayList<>(
Arrays.asList("John", "Anton","Heinz")
);
for (Iterator<String> it = names.iterator(); it.hasNext(); ) {
String name = it.next();
System.out.println("Checking: " + name);
if (name.contains("o")) names.remove(name);
}
System.out.println("names = " + names);
}
}
It seems that if you create an Iterator on CopyOnWriteArrayList, then they initially point to the same Array object (@786 in this case). But as you continue iterating through it and, say, remove an element, then the CopyOnWriteArrayList becomes a new instance (now pointing to @785) with the element removed, whereas the Iterator still keeps the old Array (@786). If I understand it correctly, then this is why CopyOnWriteArrayList allows modification as you iterate through its collection, whereas normally its not possible due to potential errors happening (skipping over elements as you delete). Am I right?
No description
No description
1 Reply
JavaBot
JavaBot9mo ago
This post has been reserved for your question.
Hey @Steadhaven! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here. 💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?