java抛Exception in thread "main" java.util.ConcurrentModificationException
Python抛RuntimeError: dictionary changed size during iteration
java代码
ArrayList<String> arr = new ArrayList<>();
arr.add("hello");
arr.add("tomorrow");
arr.add("hello1");
arr.add("tomorrow1");
for(String s: arr){
System.out.println(s);
arr.add("error");
}
Python代码
arr1 = {"a":"a","b":"b"}
for i in arr1:
print(i)
arr1["c"] = "c"
什么意思呢?就是你用我的迭代器的时候不允许添加或者删除数据。
因为他不知道添加过来的数据迭不迭代;
在集合迭代中,java提供了remove方法(iterator)和add(ListIterator),用它是不会出现异常的,对于添加数据不予迭代。
ArrayList<String> arrr = new ArrayList<>();
arrr.add("CSDN");
arrr.add("MY");
ListIterator<String> stringListIterator = arrr.listIterator();
String s;
while(stringListIterator.hasNext()){
stringListIterator.add("DOT");
System.out.println(stringListIterator.next());
}
System.out.println(arrr);
结果如下
CSDN
MY
[DOT, CSDN, DOT, MY]