许久都未写技术文章了,实在是有些怠惰了,自觉惭愧啊。
在Java中使用for循环直接删除ArrayList中的特定元素是错的,不同的for循环方式会发生不同的错误,比如泛型的for会抛出ConcurrentModificationException,而普通的for想要删除集合中重复且连续的元素则只能删除第一个。
错误原因:
我们打开JDK的ArrayList源码,看一下ArrayList中的remove方法是如何实现的(注意ArrayList中的remove有两个同名方法,只是入参不同,这里我们看的是入参为Object的remove方法):
/** 此处使用的是jdk11.0.7的代码 **/
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* {@code i} such that
* {@code Objects.equals(o, get(i))}
* (if such an element exists). Returns {@code true} if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return {@code true} if this list contained the specified element
*/
public boolean remove(Object o) {
final Object[] es = elementData;
final int size = this.size;
int i = 0;
found: {
if (o == null) {
for (; i < size; i++)
if (es[i] == null)
break found;
} else {
for (; i < size; i++)
if (o.equals(es[i]))
break found;
}
return false;
}
fastRemove(es, i);
return true;
}
/**
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(Object[] es, int i) {
modCount++;
final int newSize;
if ((newSize = size - 1) > i)
System.arraycopy(es, i + 1, es, i, newSize - i);
es[size = newSize] = null;
}
可以看到,一般情况下,程序的执行路径会走到else路径下并最终调用fastRemove方法,然后执行System.arraycopy方法,从而导致删除元素时涉及到数组元素的移动。
考虑下面这样一个ArrayList集合:
List<String> list = new ArrayList(Arrays.asList("a", "b", "b", "c", "d"));
针对普通for循环的错误写法可以想到,在遍历第一个字符串b时因为符合删除条件,所以将该元素从数组中删除,然后将后一个元素移动(也就是第二个字符串b)至当前位置,导致下一次循环遍历时后一个字符串b并没有遍历到,所以不可以以这样的方式删除。但是针对这种情况可以用倒序删除的方式来避免。
最优的解决方案:使用iterator。
List<String> list = new ArrayList(Arrays.asList("a", "b", "b", "c", "d"));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("b")) {
iterator.remove();
}
}
把这个问题扩展一下,考虑下面的代码可能会出现什么问题?
ArrayList<String> array = new ArrayList<String>();
array.add(1, "hello world");
对,就是超出界限的IndexOutOfBoundsException错误啦~