I am deleting 2nd last element of an ArrayList while iterating the same list through enhanced for-loop and I was expecting a ConcurrentModificationException however it is working fine. Kindly help me if java has provided a special case for 2nd last element.
I tried it with different indexes but it is working as expected only for the 2nd last element, it is giving unexpected result
List<Integer> list=new ArrayList<>();
list.add(2);
list.add(4);
list.add(3);
list.add(5);
for(Integer num:list) {
if(num==3) {
list.remove(num);
}
System.out.println(num);
}
Expected result: ConcurrentModificationException
Actual Result: Working fine
Iterator#nextthat is being used with the syntax suggarfor(Integer num : list)that will be actually replaced byIterator<Integer> it = list.iterator(); while(it.hasNext()) num = it.next()there's something about hasNext returning false in the first situation. IDKhasNextreturningfalsebeforenextcan be called to throw the exception - just seen on debugger - the catch is that the for-each loop is transformed to a while loop using that methodsListis, i.e. how many elements it contains, removing any element except for the second-last element throwsConcurrentModificationException.