使用增強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循環進行集合的迭代的時候其實默認使用的是迭代器,因此在循環中不能使用集合的引用變量直接操作集合,避免導致多線程並發訪問的安全性異常。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM