I got this code Snippet which is working fine.
import java.util.ConcurrentModificationException;
import java.util.*;
ArrayList<Object> s = new ArrayList<>();
s.add(null);
s.add("test");
try {
System.out.println(s + "\n");
for (Object t : s) {
System.out.println(t);
if (t == null || t.toString().isEmpty()) {
s.remove(t);
System.out.println("ObjectRemoved = " + t + "\n");
}
}
System.out.println(s + "\n");
} catch (ConcurrentModificationException e) {
System.out.println(e);
} catch (Exception e) {
System.out.println(e);
}
But after changing
s.add(null);
s.add("test");
to
s.add("test");
s.add(null);
The code throws a ConcurrentModificationException
So my question is why can I remove null if it's the first object in the list but not if it's the second one?