模板测试代码以下:html
public class ArrayListRemove { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("a"); list.add("bb"); list.add("bb"); list.add("ccc"); list.add("ccc"); list.add("ccc"); remove(list);//执行删除 //打印列表元素 for (String s : list) { System.out.println("element : " + s); } } public static void remove(ArrayList<String> list) { //TODO } }
public static void remove(ArrayList<String> list) { for (int i = 0; i < list.size(); i++) { if ("bb".equals(list.get(i))){ list.remove(i); } } }
执行结果以下:java
element : a element : bb element : ccc element : ccc element : ccc
能够发现,有一个"bb"的字符串没有被删除掉。数组
public static void remove(ArrayList<String> list) { for (String s : list) { if ("bb".equals(s)) { list.remove(s); } } }
执行结果以下:安全
Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) at java.util.ArrayList$Itr.next(ArrayList.java:851) at com.dh.yjt.SpringBootDemo.test.Collection.ArrayListRemove.remove(ArrayListRemove.java:24) at com.dh.yjt.SpringBootDemo.test.Collection.ArrayListRemove.main(ArrayListRemove.java:16)
发现抛出ConcurrentModificationException的异常。数据结构
要分析产生上述错误现象的缘由惟有翻一翻jdk的ArrayList源码,先看下ArrayList中的remove方法(注意ArrayList中的remove有两个同名方法,只是入参不一样,这里看的是入参为Object的remove方法)是怎么实现的:并发
public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; }
发现最终都会调用fastRemove(index)方法:框架
private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work }
针对错误一:测试
能够看到会执行System.arraycopy方法,致使删除元素时涉及到数组元素的移动。this
在遍历第二个元素字符串bb时由于符合删除条件,因此将该元素从数组中删除,而且将后一个元素移动(也是字符串bb)至当前位置,致使下一次循环遍历时后一个字符串bb并无遍历到,因此没法删除。spa
对System.arraycopy()是浅拷贝,不会进行递归拷贝,因此产生的结果是基本数据类型是值拷贝,对象只是引用拷贝
针对这种状况能够倒序删除的方式来避免:
由于数组倒序遍历时即便发生元素删除也不影响后序元素遍历。
针对错误二:
错误二产生的缘由倒是foreach写法是对实际的Iterable、hasNext、next方法的简写,问题一样处在上文的fastRemove方法中,能够看到第一行把modCount变量的值加一,但在ArrayList返回的迭代器(该代码在其父类AbstractList中):
public Iterator<E> iterator() { return new Itr(); }
这里返回的是AbstractList类内部的迭代器实现private class Itr implements Iterator<E>,看这个类的next方法:
public E next() { checkForComodification(); try { int i = cursor; E next = get(i); lastRet = i; cursor = i + 1; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } }
第一行checkForComodification方法:
final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }
这里会作迭代器内部修改次数检查,由于上面的remove(Object)方法把修改了modCount的值,因此才会报出并发修改异常。要避免这种状况的出现则在使用迭代器迭代时(显示或foreach的隐式)不要使用ArrayList的remove,改成用Iterator的remove便可。
public static void remove(ArrayList<String> list) { Iterator<String> it = list.iterator(); while (it.hasNext()) { String s = it.next(); if (s.equals("bb")) { it.remove(); } } }
迭代器模式:就是提供一种方法对一个容器对象中的各个元素进行访问,而又不暴露该对象容器的内部细节。
Java集合框架的集合类,咱们有时候称之为容器。容器的种类有不少种,好比ArrayList、LinkedList、HashSet...,每种容器都有本身的特色,ArrayList底层维护的是一个数组;LinkedList是链表结构的;HashSet依赖的是哈希表,每种容器都有本身特有的数据结构。
由于容器的内部结构不一样,不少时候可能不知道该怎样去遍历一个容器中的元素。因此为了使对容器内元素的操做更为简单,Java引入了迭代器模式!
把访问逻辑从不一样类型的集合类中抽取出来,从而避免向外部暴露集合的内部结构。
对于数组咱们使用的是下标来进行处理的:
int array[] = new int[3]; for (int i = 0; i < array.length; i++) { System.out.println(array[i]); }
对ArrayList的处理
List<String> list = new ArrayList<String>(); for(int i = 0 ; i < list.size() ; i++){ String string = list.get(i); }
对于这两种方式,咱们老是都知道它的内部结构,访问代码和集合自己是紧密耦合的,没法将访问逻辑从集合类和客户端代码中分离出来。不一样的集合会对应不一样的遍历方法,客户端代码没法复用。在实际应用中如何将上面两个集合整合是至关麻烦的。
因此才有Iterator,它老是用同一种逻辑来遍历集合。使得客户端自身不须要来维护集合的内部结构,全部的内部状态都由Iterator来维护。客户端不用直接和集合进行打交道,而是控制Iterator向它发送向前向后的指令,就能够遍历集合。
在Java中Iterator为一个接口,它只提供了迭代的基本规则。在JDK中它是这样定义的:对Collection进行迭代的迭代器。迭代器取代了Java Collection Framework中的Enumeration。迭代器与枚举有两点不一样:
1. 迭代器在迭代期间能够从集合中移除元素。
2. 方法名获得了改进,Enumeration的方法名称都比较长。
其接口定义以下:
package java.util; public interface Iterator<E> { boolean hasNext();//判断是否存在下一个对象元素 E next();//获取下一个元素 void remove();//移除元素 }
Java中还提供了一个Iterable接口,Iterable接口实现后的功能是‘返回’一个迭代器,咱们经常使用的实现了该接口的子接口有:Collection<E>、List<E>、Set<E>等。该接口的iterator()方法返回一个标准的Iterator实现。实现Iterable接口容许对象成为Foreach语句的目标。就能够经过foreach语句来遍历你的底层序列。
Iterable接口包含一个能产生Iterator对象的方法,而且Iterable被foreach用来在序列中移动。所以若是建立了实现Iterable接口的类,均可以将它用于foreach中。
Package java.lang; import java.util.Iterator; public interface Iterable<T> { Iterator<T> iterator(); }
使用迭代器遍历集合:
public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("张三1"); list.add("张三2"); list.add("张三3"); list.add("张三4"); List<String> linkList = new LinkedList<String>(); linkList.add("link1"); linkList.add("link2"); linkList.add("link3"); linkList.add("link4"); Set<String> set = new HashSet<String>(); set.add("set1"); set.add("set2"); set.add("set3"); set.add("set4"); //使用迭代器遍历ArrayList集合 Iterator<String> listIt = list.iterator(); while(listIt.hasNext()){ System.out.println(listIt.next()); } //使用迭代器遍历Set集合 Iterator<String> setIt = set.iterator(); while(setIt.hasNext()){ System.out.println(listIt.next()); } //使用迭代器遍历LinkedList集合 Iterator<String> linkIt = linkList.iterator(); while(linkIt.hasNext()){ System.out.println(listIt.next()); } }
使用foreach遍历集合:
List<String> list = new ArrayList<String>(); list.add("张三1"); list.add("张三2"); list.add("张三3"); list.add("张三4"); for (String string : list) { System.out.println(string); }
能够看出使用foreach遍历集合的优点在于代码更加的简洁,更不容易出错,不用关心下标的起始值和终止值。
在使用Iterator的时候禁止对所遍历的容器进行改变其大小结构的操做。例如: 在使用Iterator进行迭代时,若是对集合进行了add、remove操做就会出现ConcurrentModificationException异常。
List<String> list = new ArrayList<String>(); list.add("张三1"); list.add("张三2"); list.add("张三3"); list.add("张三4"); //使用迭代器遍历ArrayList集合 Iterator<String> listIt = list.iterator(); while(listIt.hasNext()){ Object obj = listIt.next(); if(obj.equals("张三3")){ list.remove(obj);//调用list的remove方法 } }
由于在你迭代以前,迭代器已经被经过list.itertor()建立出来了,若是在迭代的过程当中,又对list进行了改变其容器大小的操做,那么Java就会给出异常。
由于此时Iterator对象已经没法主动同步list作出的改变,Java会认为你作出这样的操做是线程不安全的,就会给出善意的提醒(抛出ConcurrentModificationException异常)
Iterator的实现源码:
private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
经过查看源码发现原来检查并抛出异常的是checkForComodification()方法。
在ArrayList中modCount是当前集合的版本号,每次修改(增、删)集合都会加1;expectedModCount是当前迭代器的版本号,在迭代器实例化时初始化为modCount。
咱们看到在checkForComodification()方法中就是在验证modCount的值和expectedModCount的值是否相等,因此当你在调用了ArrayList.add()或者ArrayList.remove()时,只更新了modCount的状态,而迭代器中的expectedModCount未同步,所以才会致使再次调用Iterator.next()方法时抛出异常。
可是为何使用Iterator.remove()就没有问题呢?经过源码发现,在Iterator的remove()中同步了expectedModCount的值,因此当你下次再调用next()的时候,检查不会抛出异常。
使用该机制的主要目的是为了实现ArrayList中的快速失败机制(fail-fast),在Java集合中较大一部分集合是存在快速失败机制的。
快速失败机制产生的条件:当多个线程对Collection进行操做时,若其中某一个线程经过Iterator遍历集合时,该集合的内容被其余线程所改变,则会抛出ConcurrentModificationException异常。
因此要保证在使用Iterator遍历集合的时候不出错误,就应该保证在遍历集合的过程当中不会对集合产生结构上的修改。
使用Foreach时对集合的结构进行修改会出现异常:
上面咱们说了实现了Iterable接口的类就能够经过Foreach遍历,那是由于foreach要依赖于Iterable接口返回的Iterator对象,因此从本质上来说,Foreach其实就是在使用迭代器,在使用foreach遍历时对集合的结构进行修改,和在使用Iterator遍历时对集合结构进行修改本质上是同样的。因此一样的也会抛出异常,执行快速失败机制。
foreach是JDK1.5新增长的一个循环结构,foreach的出现是为了简化咱们遍历集合的行为。
for循环与迭代器的对比:
* 效率上各有各的优点:
> ArrayList对随机访问比较快,而for循环中使用的get()方法,采用的便是随机访问的方法,所以在ArrayList里for循环快。
> LinkedList则是顺序访问比较快,Iterator中的next()方法采用的是顺序访问方法,所以在LinkedList里使用Iterator较快。
> 主要仍是要依据集合的数据结构不一样的判断。
参考:
Java中ArrayList循环遍历并删除元素的陷阱 https://www.iteye.com/blog/tyrion-2203335
深刻理解Java中的迭代器 https://www.cnblogs.com/zyuze/p/7726582.html