While using foreach with ArrayList, I know that using add/remove method will not work as it will throw concurrent modification exception, but then why am I able to change the value using the set method within the same foreach loop ?
Here is the sample code :
for (Integer integer : arr) {
if (integer==2) {
arr.set(1, 6);
}
System.out.println(integer);
}
System.out.println(arr);
If we will change arr.add() then it will throw an error, but with set it is working fine, what's the reason here ?
According to the docs, CME is thrown if the list is structurally modified after the iterator is created. Since set()
only replaces an existing element, no structural modification takes place and the exception is not thrown.
There is a difference in the implementation. When the length of the list is modified (which add
method does) the iterator returned by ArrayList throws ConcurrentModificationException because it checks the length of the array. While the set
method does not modify the length of the array thus no ConcurrentModificationException is thrown.
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