I am using the following code to loop through an arraylist and then removing one element from the arraylist.
Here i'm expecting ConcurrentModificationException. But didn't get that exception. especially when you are checking condition with (n-1)th element. Please help me. Below is my code.
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) {
arrayList.add(5 * i);
}
System.out.println(arrayList);
Iterator<Integer> iterator = arrayList.iterator();
while (iterator.hasNext()) {
Integer temp = iterator.next();
if (temp == 45) {
/**
* temp == 40 (then i'm getting *ConcurrentModificationException) why not i'm
* getting ConcurrentModificationException if (temp == 45)
*/
arrayList.remove(1);
}
}
System.out.println(arrayList);
Thanks in Advance
The implementation makes a best effort to detect concurrent modification, but there are cases where it fails to do so.
The
Iterator
implementation returned forArrayList
'sIterator
checks for concurrent modification innext()
andremove()
, but not inhasNext()
, whose logic is:Since you removed an element when the
Iterator
's cursor was at the element before the last element, the removal causeshasNext()
to returnfalse
(sincesize
becomes equal tocursor
after the removal), which ends your loop without throwing an exception.