arraylist java使用,如何使用Java ArrayList?

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值