import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
// 涛哥 1609251501
// 如何不用 List.clear() 方法 就清空 list 中的 所有元素.
public class MyList {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("1","2","3","4"));
Iterator<String> it = list.iterator();
while(it.hasNext()) {
it.next(); // return ; cursor++;
it.remove(); // cursor
}
System.out.println(list);
}
}
代码分析:
it.next() 源码中: 先返回 当前 cursor 所指向的 value, 之后 cursor 在 自加;
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];
}
it.remove() 源码中: AraryList.remove() 方法 删除元素的方法是 将 后面的元素 全部向前挪动一个位置;且 cursor 等于上一次 更改位置的index;
public void remove() { // ArrayList$Itr.remove()
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet); // 调用 ArrayList.remove() 方法
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public E remove(int index) { // ArrayList.remove()方法
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;
}