您的位置:首页 > 职场人生

面试题:Java中ArrayList循环遍历并删除元素的陷阱

2017-04-12 21:55 363 查看
面试官问到这个问题时,当时有点没反应过来,多了解哈

先看测试案例:

import java.util.ArrayList;

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++) {
String s = list.get(i);
if (s.equals("bb")) {
list.remove(s);
}
}
}


这种最普通的循环写法执行后会发现有一个“bb”的字符串没有删掉。

错误写法示例二:

public static void remove(ArrayList<String> list) {
for (String s : list) {
if (s.equals("bb")) {
list.remove(s);
}
}
}


这种for each写法会发现报出著名的并发修改异常Java.util.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;
}


按一般执行路径会走到else路径下最终调用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; // Let gc do its work
}


可以看到会执行System.arraycopy方法,导致删除元素时涉及到数组元素的移动。针对错误写法一,在遍历第二个元素字符串bb时因为符合删除条件,所以将该元素从数组中删除,并且将后一个元素移动(也是字符串bb)至当前位置,导致下一次循环遍历时后一个字符串bb并没有遍历到,所以无法删除。针对这种情况可以倒序删除的方式来避免。

解决办法如下:

public static void remove(ArrayList<String> list){
for(int i=list.size()-1;i>=0;i--){
String s=list.get(i);
if(s.equals("bb")){
list.remove(s);
}
}
}


因为数组倒序遍历时即使发生元素删除也不影响后序元素遍历。

而错误二产生的原因却是for each增强for循环写法是对实际的Iterator、hasNext、next方法的简写,问题同样处在上文的fastRemove中,可以看到第一行把modCount变量的值加1,但在ArrayList返回的迭代器(该代码在其父类AbstractList中)

public Iterator<E> iterator() {
return new Itr();
}


这里返回的是AbstractList类内部的迭代器实现private class Itr implements Iterator ,看这个类的next方法:

public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}


第一行checkForComodification方法:

final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}


这里会做迭代器内部修改次数检查,因为你上面的remove(Object)方法把修改了modCount的值,所以才会报出并发修改异常。要避免这种情况的出现,则在使用迭代器迭代时(显式或for each的隐式)不要使用ArrayList的remove,改用Iterator的remove即可。

final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}


总结:

错误原因都是ArrayList集合中remove方法底层的源码中有一个fastRemove(index)方法,然后会有一个modCount++的操作,然后在ArratList内部的迭代器中有一个checkForComodification操作,也就是检查modCount是否改变,如果改变了,就抛出并发修改错误。

同样的在For each增强for循环中,也是利用了ArrayList自身的Iterator迭代器,也是会出现这样的错误。

对于一般的for遍历,可能并没有删除要修改的数,可以采用倒序删除的写法改正这个错误。

对于增强for循环中的遍历,会抛出并发修改异常,使用Iterator自己的remove方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息