1. 程式人生 > >java.util.ConcurrentModificationException :Java List 併發操作異常測試

java.util.ConcurrentModificationException :Java List 併發操作異常測試

        List<String> list = new LinkedList<String>();

          Collections.addAll(list, "a", "b", "c", "d", "e");

          // 方式二:通過迭代器遍歷,同時呼叫迭代器的remove()方法刪除元素,結果正常

          for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {

               String string = iterator.next();

               if ("b".equals(string)) {

                    System.out.println("---使用迭代器的remove()方法,刪除ArrayList集合中的元素:" + string);

                    iterator.remove();

               }

          }

          System.out.println("list.size() ==> " + list.size());

          // 方式三:通過下標for遍歷List,每次動態獲取size,

          // 同時呼叫List集合的remove(int index)方法刪除指定下標的元素,結果正常

          // 若開始獲取size大小記錄,則會產生陣列下標越界異常,

          // for (int i = 0,len = list.size(); i < len; i++) {

          for (int i = 0; i < list.size(); i++) {

               String string = list.get(i);

               if ("c".equals(string)) {

                    System.out.println("---根據下標index刪除ArrayList集合中的元素:" + string);

                    list.remove(i);

               }

          }

          System.out.println("list.size() ==> " + list.size());

          // 方式一: 增強for遍歷,同時呼叫remove(Object value),刪除List集合中元素,

          // 出現異常java.util.ConcurrentModificationException

          // 注意:1.此種方式刪除List末尾位置下標元素不會有異常

          // 2.當List集合只有一個元素,刪除也會有異常,如方式四

          for (String string : list) {

               if ("a".equals(string)) {

                    System.out.println("---根據value刪除ArrayList集合中的元素:" + string);

                    list.remove(string);

               }

          }

          System.out.println("list.size() ==> " + list.size());

          // 方式四

          List<String> anElementList = new ArrayList<String>();

          Collections.addAll(anElementList, "a");

          for (String string : anElementList) {

               anElementList.remove(string);

          }

          System.out.println("anElementList.size() ==> " + anElementList.size());