标签:col next check ignore dex current png void return
普通循环:利用index实现
增强型循环:通过迭代器实现
示例代码:
public class ArrayListTest { public static void main(String[] args) { normalFor(getList()); //普通循环 iterator(getList()); //增强循环-迭代器 forEach(getList()); //增强循环-foreach方式 } //普通循环 private static void normalFor(List<String> list) { for (int i = 0 ; i < list.size() ; i++){ if ("b".equalsIgnoreCase(list.get(i)) || "d".equalsIgnoreCase(list.get(i))){ list.remove(i); } } System.out.println("normalFor:"+JSONObject.toJSONString(list)); } //增强循环-迭代器 private static void iterator(List<String> list) { Iterator iterator = list.iterator(); while (iterator.hasNext()){ String str = (String) iterator.next(); if ("b".equalsIgnoreCase(str) || "d".equalsIgnoreCase(str)){ iterator.remove(); } } System.out.println("iterator:"+JSONObject.toJSONString(list)); } //增强循环-foreach方式 private static void forEach(List<String> list) { for (String str : list){ if ("b".equalsIgnoreCase(str) || "d".equalsIgnoreCase(str)){ list.remove("b"); } } System.out.println("forEach:"+JSONObject.toJSONString(list)); } private static List<String> getList(){ List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.add("e"); return list; } }
输出
normalFor:["a","c","d","e"] iterator:["a","d","e"] 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) at com.qxy.collection.ArrayListTest.forEach(ArrayListTest.java:47) at com.qxy.collection.ArrayListTest.main(ArrayListTest.java:21) Process finished with exit code 1
从上边可以看出
类型 | 输出结果 |
普通循环 | 正常输出,结果错误 |
增强循环-迭代器 | 正常输出,结果正确 |
增强循环-foreach | 报异常 |
普通循环
普通循环,底层是数组,在remove操作时,被删除元素的后边所有的元素,会往前挪挪一位。咱们还是看图,比较直观
当第一次删除时,此时的 i = 1,b正常删除,c、d、e此时都往前挪了一位,然后执行了 i+1 变成了2,也就是d 的位置,一直往后都没匹配到c,所以导致c为正常删除。
增强循环-迭代器
在分析之前,我们先来看看反编译之后的代代码
public class ArrayListTest { ... private static void iterator(List<String> list) { Iterator iterator = list.iterator(); while(true) { String str; do { if (!iterator.hasNext()) { System.out.println("iterator:" + JSONObject.toJSONString(list)); return; } str = (String)iterator.next(); } while(!"b".equalsIgnoreCase(str) && !"c".equalsIgnoreCase(str)); iterator.remove(); } } private static void forEach(List<String> list) { Iterator var1 = list.iterator(); while(true) { String str; do { if (!var1.hasNext()) { System.out.println("forEach:" + JSONObject.toJSONString(list)); return; } str = (String)var1.next(); } while(!"b".equalsIgnoreCase(str) && !"c".equalsIgnoreCase(str)); list.remove(str); } } ... }
标签:col next check ignore dex current png void return
原文地址:https://www.cnblogs.com/qxynotebook/p/11253257.html