java foreach list.remove()一定会报错吗
来两个例子热身。
String[] arrays = {"1", "2", "3", "5" ,"4"};
List<String> list = new ArrayList<>(Arrays.asList(arrays));
for (String str : list) {
//remove "1","2","3","4"会报错吗
if (str.equals("1")) {
list.remove(str);
}
}
答案:会
String[] arrays = {"1", "2", "3", "5" ,"4"};
List<String> list = new ArrayList<>(Arrays.asList(arrays));
for (String str : list) {
// remove "5"会报错吗?
if (str.equals("5")) {
list.remove(str);
}
}
答案: 不会
但是不能在foreach里面这样做
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
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
public boolean hasNext() {
return cursor != size;
}
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];
}
ArrayList总共有7种remove方法
remove方法的时序图
public boolean remove(Object o) {
if (o == null) {
// 找到为null的索引 i,然后remove(int i);
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
// 此处调用
fastRemove(index);
return true;
}
}
return false;
}