问题
Please, I try to add item to arrayList like example below:
ArrayList<Integer> 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?
回答1:
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.
回答2:
You cannot modify the list while iterating through a for..each loop. You can rewrite your code by using a second list.
ArrayList<Integer> list = new ArrayList<>();
list.add(2);
list.add(5);
list.add(7);
ArrayList<Integer> squareList = new ArrayList<>();
squareList.addAll(list)
for (int i : list){
if((i%2) == 0){
squareList.add(i*i);
}
}
回答3:
You're modifying the same list you are looping through. You should be creating a new list to hold the result of your operation.
List<Integer> list = new ArrayList<>();
List<Integer> squares = new ArrayList<>();
list.add(2);
list.add(5);
list.add(7);
for (int i : list) {
if ((i % 2) == 0) {
squares.add(i * i);
}
}
System.out.println(squares);
Also in Java 8
List<Integer> squares = Stream.of(2, 5, 7)
.filter(i -> i % 2 == 0)
.map(i -> i * i)
.collect(Collectors.toList());
来源:https://stackoverflow.com/questions/27493402/how-to-work-with-java-arraylist