zoukankan      html  css  js  c++  java
  • 使用增强for循环遍历集合的时候操作集合的问题?

     1     // 遍历一个list
     2     public static void printList(List<String> list){
     3         for (String string : list) {
     4             list.add("eeee");    // 运行错误
     5             System.out.println(string);
     6         }
     7         System.out.println("遍历中: "+list);
     8     }
     9 异常信息如下:
    10 Exception in thread "main" java.util.ConcurrentModificationException
    11 模拟基础班看过的场景:
    12     public static void main(String[] args) {
    13         List<String> list = new ArrayList<String>();
    14         list.add("aaaa");
    15         list.add("bbbb");
    16         list.add("cccc");
    17         list.add("dddd");
    18         
    19         Iterator<String> it = list.iterator();
    20         while(it.hasNext()){
    21             list.add("yyyy");
    22             String str = it.next();
    23             System.out.println(str);
    24         }
    25     }
    26 运行异常:
    27 Exception in thread "main" java.util.ConcurrentModificationException
    28 总结;
    29 在使用增强for循环进行集合的迭代的时候其实默认使用的是迭代器,因此在循环中不能使用集合的引用变量直接操作集合,避免导致多线程并发访问的安全性异常。
  • 相关阅读:
    线性反馈系统
    静磁场
    平面波的传播
    Partition does not end on cylinder boundary
    FFTW简介及使用
    EINTR、ERESTARTSYS和SIGINT
    凉面
    linux Shell编程
    Linux From Scratch [2]
    Linux From Scratch [1]
  • 原文地址:https://www.cnblogs.com/friends-wf/p/3718760.html
Copyright © 2011-2022 走看看