標籤:lis nbsp expand default state throw lin object for
注:代碼中的注釋是我的個人理解,如果有誤還請指出。
AbstractList
add操作將元素添加到列表末尾。
public boolean add(E e) { add(size(), e);//size() return true; }
remove操作將指定元素移除列表,通過Iterator的remove方法實現。
public boolean remove(Object o) { Iterator<E> it = iterator(); if (o==null) { while (it.hasNext()) { if (it.next()==null) { it.remove();//調用iterator的remove方法 return true; } } } else { while (it.hasNext()) { if (o.equals(it.next())) { it.remove(); return true; } } } return false; }/*==========Iterator的remove方法============*//*This method can be called only once per call to {@link #next}.*//*此方法只能在next()方法調用後調用,因為噹噹前指標指向的記憶體中沒有元素時會拋出IllegalStateException*/? default void remove() { throw new UnsupportedOperationException("remove"); }
clear操作通過調用iterator的remove移除列表中的所有元素
public void clear() { Iterator<E> it = iterator(); while (it.hasNext()) { it.next();//先調用next it.remove();//再移除 } }AbstractList.Itr
next()
public E next() { checkForComodification(); try { int i = cursor;//擷取指標 E next = get(i);//擷取指標對應的元素 lastRet = i;//最近調用過next()的元素的index cursor = i + 1;//指標右移 return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } }
remove()
?
public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification();? try { AbstractList.this.remove(lastRet);//移除上一次next()或者previous()的元素,列表後面的元素依次左移 if (lastRet < cursor)//如果lastRet小於cursor則說明是next() cursor--;//指標左移 lastRet = -1;//重設為-1 expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } }
AbstractList.ListItr
previous()
public E previous() { checkForComodification(); try { int i = cursor - 1;//擷取當前指標的上一個元素的index E previous = get(i);//擷取該元素 lastRet = cursor = i;//cursor指標左移,將lastRet設定為i return previous; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } }
add()
public void add(E e) { checkForComodification();? try { int i = cursor;//擷取當前指標所處的位置 AbstractList.this.add(i, e);//插入到i處 lastRet = -1; cursor = i + 1;//指標右移,以保持指標所指的元素不變 expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } }
java源碼筆記-----AbstractList