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<Integer> firstList = new ArrayList<>();
//add numbers to firstList
List<Integer> 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.