如何不用 List.clear() 方法 就清空 list 中的 所有元素(中兴面试)
生活随笔
收集整理的這篇文章主要介紹了
如何不用 List.clear() 方法 就清空 list 中的 所有元素(中兴面试)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 workreturn oldValue;}
總結
以上是生活随笔為你收集整理的如何不用 List.clear() 方法 就清空 list 中的 所有元素(中兴面试)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 江清月近人的前一句是什么 江清月近人上一
- 下一篇: 在 eclipse 中 设置 jvm 的