Please, I try to add item to arrayList like example below:
ArrayList list = new ArrayList<>();
list.add(2);
list.add(5);
list.add(7);
for(int i : list ){
if((i%2) == 0){
list.add(i*i);
}
}
but it throws an exception
java.util.ConcurrentModificationException
Could you please advice how can I add item like this or what kind of list (container) is to be used correctly?
解决方案
Use a regular for loop. Enhanced for loops do not allow you to modify the list (add/remove) while iterating over it:
for(int i = 0; i < list.size(); i++){
int currentNumber = list.get(i);
if((currentNumber % 2) == 0){
list.add(currentNumber * currentNumber);
}
}
As @MartinWoolstenhulme mentioned, this loop will not end. We iterate based on the size of the array, but since we add to the list while looping through it, it'll continue to grow in size and never end.
To avoid this, use another list. With this tactic, you no longer add to the list you are looping through. Since you are no longer modifying it (adding to it), you can use an enhanced for loop:
List firstList = new ArrayList<>();
//add numbers to firstList
List secondList = new ArrayList<>();
for(Integer i : firstList) {
if((i % 2) == 0) {
secondList.add(i * i);
}
}
The reason I use Integer instead of int for the loop is to avoid auto-boxing and unboxing between object and primitive.