Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add/remove method vs set method in ArrayList

Tags:

java

arraylist

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 ?

like image 691
Hiren Avatar asked Jan 01 '23 13:01

Hiren


2 Answers

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.

like image 164
shmosel Avatar answered Jan 05 '23 16:01

shmosel


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.

like image 30
Akhil Bojedla Avatar answered Jan 05 '23 15:01

Akhil Bojedla