I was playing with List and come across strange behavior.
As We know that while iterating over List we should not remove an element from that list. And if we will try to remove an element from that List while iterating then It will throw an exception but in this scenario, it does not throw an exception and remove an element from the list while iterating. [But it only remove the first element from the list]
Example:
Obj obj = new Obj();
obj.s = "one";
Obj obj1 = new Obj();
obj1.s = "two";
List<Obj> l = new ArrayList<Obj>(Arrays.asList(obj, obj1));
for (Obj a : l) {
l.remove(a);
}
l.forEach(System.out::println);
static class Obj {
String s = "";
@Override
public String toString() {
return s;
}
}
Output:
two
I want to know that why this not throwing an exception.
Then I made some changes in my program and try to delete an element from a list then it throws an exception. Please check below code.
Example:
for (Obj a : l) {
if (a.s.equals("two")) {
l.remove(a);
}
}
Output:
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.base/java.util.ArrayList$Itr.next(Unknown Source)
at main.java.practice.test.Experiment.main(Experiment.java:17)
And In Second program, If you will change the condition from a.s.equals("two)"
to a.s.equals("one")
Then it will not throw an exception. If anyone know the answer please help.
Example:
for (Obj a : l) {
if (a.s.equals("one")) {
l.remove(a);
}
}
l.forEach(System.out::println);
Output:
two
Does anyone know the actual behavior of the list in java?