ArrayList循环遍历并删除元素的常见陷阱

ArrayList循环遍历并删除元素的常见陷阱

栏目:Java基础 做者:admin 日期:2015-04-18 评论:2点击: 1,666 次 java

在工做和学习中,常常碰到删除ArrayList里面的某个元素,看似一个很简单的问题,却很容易出bug。不妨把这个问题当作一道面试题目,我想必定能难道很多的人。今天就给你们说一下在ArrayList循环遍历并删除元素的问题。首先请看下面的例子: 面试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java . util . ArrayList ;
public class ArrayListRemove
{
public static void main ( String [ ] args )
{
ArrayList < String > list = new ArrayList < String > ( ) ;
list . add ( "a" ) ;
list . add ( "b" ) ;
list . add ( "b" ) ;
list . add ( "c" ) ;
list . add ( "c" ) ;
list . add ( "c" ) ;
remove ( list ) ;
 
for ( String s : list )
{
System . out . println ( "element : " + s ) ;
}
}
public static void remove ( ArrayList < String > list )
{
// TODO:
}
}

若是要想删除list的b字符,有下面两种常见的错误例子: swift

错误写法实例一: 数组

1
2
3
4
5
6
7
8
9
10
11
public static void remove ( ArrayList < String > list )
{
for ( int i = 0 ; i < list . size ( ) ; i ++ )
{
String s = list . get ( i ) ;
if ( s . equals ( "b" ) )
{
list . remove ( s ) ;
}
}
}

错误的缘由:这种最普通的循环写法执行后会发现第二个“b”的字符串没有删掉。 并发

错误写法实例二: 学习

1
2
3
4
5
6
7
8
9
10
public static void remove ( ArrayList < String > list )
{
for ( String s : list )
{
if ( s . equals ( "b" ) )
{
list . remove ( s ) ;
}
}
}

错误的缘由:这种for-each写法会报出著名的并发修改异常:java.util.ConcurrentModificationException。 spa

先解释一下实例一的错误缘由。翻开JDK的ArrayList源码,先看下ArrayList中的remove方法(注意ArrayList中的remove有两个同名方法,只是入参不一样,这里看的是入参为Object的remove方法)是怎么实现的: .net

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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路径下最终调用faseRemove方法: element

1
2
3
4
5
6
7
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方法,致使删除元素时涉及到数组元素的移动。针对错误写法一,在遍历第一个字符串b时由于符合删除条件,因此将该元素从数组中删除,而且将后一个元素移动(也就是第二个字符串b)至当前位置,致使下一次循环遍历时后一个字符串b并无遍历到,因此没法删除。针对这种状况能够倒序删除的方式来避免: rem

1
2
3
4
5
6
7
8
9
10
11
public static void remove ( ArrayList < String > list )
{
for ( int i = list . size ( ) - 1 ; i >= 0 ; i -- )
{
String s = list . get ( i ) ;
if ( s . equals ( "b" ) )
{
list . remove ( s ) ;
}
}
}

由于数组倒序遍历时即便发生元素删除也不影响后序元素遍历。

接着解释一下实例二的错误缘由。错误二产生的缘由倒是foreach写法是对实际的Iterable、hasNext、next方法的简写,问题一样处在上文的fastRemove方法中,能够看到第一行把modCount变量的值加一,但在ArrayList返回的迭代器(该代码在其父类AbstractList中):

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

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

1
2
3
4
5
6
7
8
9
10
11
public E next ( ) {
checkForComodification ( ) ;
try {
E next = get ( cursor ) ;
lastRet = cursor ++ ;
return next ;
} catch ( IndexOutOfBoundsException e ) {
checkForComodification ( ) ;
throw new NoSuchElementException ( ) ;
}
}

第一行checkForComodification方法:

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

这里会作迭代器内部修改次数检查,由于上面的remove(Object)方法修改了modCount的值,因此才会报出并发修改异常。要避免这种状况的出现则在使用迭代器迭代时(显示或for-each的隐式)不要使用ArrayList的remove,改成用Iterator的remove便可。

1
2
3
4
5
6
7
8
9
10
11
12
public static void remove ( ArrayList < String > list )
{
Iterator < String > it = list . iterator ( ) ;
while ( it . hasNext ( ) )
{
String s = it . next ( ) ;
if ( s . equals ( "b" ) )
{
it . remove ( ) ;
}
}
}
相关文章
相关标签/搜索