Java增强for的本质???
在java集合的体系中,增强for的本质是一个简化版的迭代器,既可以用来遍历集合,还可以用来遍历数组。下面通过深究其内部底层实现,有如下简单代码
Collection<String> collection=new ArrayList<>();
collection.add("张三1");
collection.add("张三2");
collection.add("张三3");
for (String s : collection) {
System.out.println(s);
}
通过debug调试,可知第一步返回一个Ttr()类;  这个类实现了Iterator接口  调用hasNext()方法  最后调用next()方法.  如果在增强for循环中对集合进行操作,比如:
for (String s : collection) {
System.out.println(s);
collection.add(“a”);
}
跟踪如下代码,就会报错java.util.ConcurrentModificationException
注意: 1、不要在增强for循环里进行元素的remove/add操作,移除元素使用Iterator接口中的remove()方法,如果并发操作,需要对Iterator对象加锁
**
正例:
Iterator<Object> iterator = list.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
if(删除元素的条件){
iterator.remove();
}
}
反例:
List<String> list1=new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
for (String s : list1) {
if(s.equals("a")){
list1.remove(s);
}
}
|