How to work with Java ArrayList?

房东的猫 提交于 2020-06-27 04:27:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!