I have read an article regarding removing elements from Collections from this link
As per my understanding iterator remove method prevents Concurrent modification exception then remove method of Collection.But when i try to run the below codde i am unable to get concurrentmoficationexception
List dayList= new ArrayList();
dayList.add("Sunday");
dayList.add("Monday");
dayList.add("Tuesday");
dayList.add("Wednesday");
dayList.remove("Tuesday");
Iterator itr=dayList.iterator();
while(itr.hasNext())
{
Object testList=itr.next();
if(testList.equals("Monday"))
{
dayList.remove(testList);
}
}
System.out.println(dayList);
}
Can anyone explain what is happening behind the scene in this code?
To Avoid ConcurrentModificationException in single-threaded environment. You can use the iterator remove() function to remove the object from underlying collection object. But in this case, you can remove the same object and not any other object from the list.
Notice that iterator. remove() doesn't throw an exception by itself because it is able to update both the internal state of itself and the collection. Calling remove() on two iterators of the same instance collection would throw, however, because it would leave one of the iterators in an inconsistent state.
The ConcurrentModificationException occurs when an object is tried to be modified concurrently when it is not permissible. This exception usually comes when one is working with Java Collection classes. For Example - It is not permissible for a thread to modify a Collection when some other thread is iterating over it.
The exception means "the structure of the map was modified while I was iterating on it, so I don't know what to do now". To allow concurrent modification and iteration on the map inside the sender object, that map should be a ConcurrentHashMap .
The fail-fast behavior of an iterator cannot be guaranteed. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. The iterator may or may not detect the invalid usage. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With