Java循环遍历中直接修改遍历对象
Java 循环遍历中直接修改遍历对象如下,会报异常:
for (ShopBaseInfo sp: sourceList) {
if(sp.getId()==5){
sourceList.remove(sp);
}
}
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
如果有需要修改循环遍历对象的需求,可以使用迭代器来实现,代码如下:
/**
* @author jack
**/
public class ForLoopTest {
public static void main(String[] args) {
List<ShopBaseInfo> sourceList = new ArrayList<ShopBaseInfo>();
ShopBaseInfo shop = null;
for (long i=0 ;i<8;i++){
shop = new ShopBaseInfo();
shop.setId(i);
shop.setShopName("shop"+i);
sourceList.add(shop);
}
System.out.println("sourcelist init --------");
printList(sourceList);
/* for (ShopBaseInfo sp: sourceList) {
if(sp.getId()==5){
sourceList.remove(sp);
}
}*/
Iterator<ShopBaseInfo> iterator = sourceList.iterator();
while (iterator.hasNext()) {
ShopBaseInfo sbi = iterator.next();
if(sbi.getId() == 5){
iterator.remove();
}
}
System.out.println("after sourcelist remove --------");
printList(sourceList);
}
private static void printList(List<ShopBaseInfo> sourceList){
StringBuilder builder = new StringBuilder();
for (ShopBaseInfo shop : sourceList ) {
builder.append("->").append(shop.getShopName());
}
System.out.println(builder);
}
}
运行结果:
sourcelist init --------
->shop0->shop1->shop2->shop3->shop4->shop5->shop6->shop7
after sourcelist remove --------
->shop0->shop1->shop2->shop3->shop4->shop6->shop7