foreach/增强for循环 中 使用iterator.remove();
Set<String> set = new HashSet<>();
set.add("a");
set.add("b");
Iterator<String> iterator = set.iterator();
for (String string : set) {
iterator.next();
iterator.remove();
}
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1597)
at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1620)
at lanqiao1.Main.main(Main.java:21)
仍会报错
原因大概是 foreach/增强for循环 实际上是一个iterator
而我们又定义了另外一个iterator让其next()和remove(),相当于两个iterator同时操作,Concurrent并发修改异常
很多文章使用反编译工具 反编译 foreach/增强for循环 的.class文件,来探究 底层是用迭代器模式进行遍历的
但是,不同反编译工具 反编译出来的结果似乎是不同的
我用jd-gui 反编译出来仍是 foreach/增强for循环
使用javap -verbose来尝试,发现没有源码,比较混乱
#32 = InterfaceMethodref #25.#33 // java/util/Set.iterator:()Ljava/util/Iterator;
#33 = NameAndType #34:#35 // iterator:()Ljava/util/Iterator;
#34 = Utf8 iterator
#35 = Utf8 ()Ljava/util/Iterator;
#36 = InterfaceMethodref #37.#39 // java/util/Iterator.next:()Ljava/lang/Object;
#37 = Class #38 // java/util/Iterator
#38 = Utf8 java/util/Iterator
#39 = NameAndType #40:#41 // next:()Ljava/lang/Object;
#40 = Utf8 next
#41 = Utf8 ()Ljava/lang/Object;
#42 = Class #43 // java/lang/String
#43 = Utf8 java/lang/String
#44 = InterfaceMethodref #37.#45 // java/util/Iterator.remove:()V
#45 = NameAndType #46:#6 // remove:()V
#46 = Utf8 remove
#47 = InterfaceMethodref #37.#48 // java/util/Iterator.hasNext:()Z
#48 = NameAndType #49:#50 // hasNext:()Z
#49 = Utf8 hasNext
#50 = Utf8 ()Z