关于ArrayList遍历删除有三种操作方式,一是for循环,二是foreach,三是迭代器,然而三种方式的结果并不是都能达到预期。
第一种方式:for循环删除
private static void forRemove(List<String> list) {
for (int i = 0; i < list.size(); i++) {
if ("b".equals(list.get(i)) || "c".equals(list.get(i))) {
list.remove(i);
}
}
}
第二种方式: foreach遍历删除
private static void foreachRemove(List<String> list) {
for (String s : list) {
if ("b".equals(s) || "c".equals(s)) {
list.remove(s);
}
}
}
第三种方式:迭代器删除
private static void iteRemove(List<String> list){
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()){
String next = iterator.next();
if ("b".equals(next) || "c".equals(next)) {
iterator.remove();
}
}
}
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
假设这是我们的输入,大家不妨先思考一下三种方式的结果分别是什么?
首先来分析第一种情况,直接调用remove
看源码
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
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
return oldValue;
}
这是ArrayList的remove方法,简单易懂,就是将给定index位置之后的元素都向前移动一位,达到删除给定位置元素的目的。
分析下第一种方式,当i=1时,我们删除了元素b,这时list变成了[a,c,d,e],for循环继续往下进行,i=2,for循环找到了第三个元素d,发现不匹配我们的if条件,没有进行删除,这样就跳过了我们想删除的c,所以第一种方式最后结果是[a, c, d, e],并没有达到我们的程序预期目的
接下来看第二种方式 foreach
这里要补充一点,foreach循环,编译器编译后,也是一迭代器的方式循环,我们看一下编译后的方法
private static void foreachRemove(List<String> list) {
Iterator var1 = list.iterator();
while(true) {
String s;
do {
if (!var1.hasNext()) {
return;
}
s = (String)var1.next();
} while(!"b".equals(s) && !"c".equals(s));
list.remove(s);
}
}
接下来我们看一下这里调的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;
}
这是ArrayList重载的一个remove方法,参数时传入的元素,这里我们可以看到又继续调了fastRemove方法来进行删除操作
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
}
对比之前的remove(index)方法,两个方法操作其实一样,除了fastRemove没有返回原来的值,这里还有一个重要的点,就是modCount++,这个modCount是干嘛用的呢,我们继续往下看。
上面编译器编译后的文件中,我们看到获取元素是通过迭代器的next()方法去获取的,我们来看下迭代器的几个关键方法
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];
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
我们看到迭代器其实就是维护一个游标cursor,不断往下遍历集合。然后我们注意到next方法首先会调用checkForComodification,检查集合是否被修改过。
我们看checkForComodification,就是判断modCount是否等于expectedModCount,这里的expectedModCount就是我们迭代器初始化的时候赋值的,expectedModCount = modCount,回到刚才我们提到的fastRemove(index)方法,里面有一个modCount++,所以集合每次删除元素,这个modCount值就会发生变化,下次再调用next方法,就会抛出ConcurrentModificationException异常。
至于这里抛出ConcurrentModificationException这个异常,是一种fail-fast机制,快速失败的机制,就是两个线程一起遍历操作集合时,如果修改了集合数据,那么另一个地方再次操作集合时,直接抛出异常;(当然多线程操作集合也不建议使用线程不安全的ArrayList)
所以第二种方式foreach遍历删除,结果是抛出ConcurrentModificationException
####接下来看第三种方式 迭代器遍历删除
可以看出这种方式和第二种方式编译后类似,一个不同的地方是这里用的迭代器的删除方法,iterator.remove();
来看一下迭代器的remove方法
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();
}
}
删除当前元素,并且把游标回到当前位置,这样就避免了第一种方式出现的跳过一个元素的结果;
lastRet = -1,如果连着两次调用remove则会抛出非法参数异常(lastRet会在调用next方法时被赋值为cursor的值,可以看上面贴的next源码);
expectedModCount = modCount,那么第二种方式里遇到的ConcurrentModificationException也解决了。
ok,以上就是关于ArrayList的几种remove方式的分析,希望可以帮助大家更好的理解其中的细节。