Container-ListedListは、指定された位置要素のソースコード分析を削除します(11)
-
インデックスに基づいて要素を削除する
import java.util.LinkedList; import java.util.List; public class LinkedListTest { public static void main(String[] args) { List<String> list= new LinkedList<>(); //添加元素 list.add("a"); list.add("b"); list.add("c"); list.add("a"); list.add(2,"aaaa"); //根据索引删除元素 list.remove(2); ] }
-
removeのソースコードを見て、最初にCtrlを入力します
E remove(int index);
-
Ctrl + Altを使用して、removeメソッドのLinkedListインターフェース実装クラスを選択します
/** * Removes the element at the specified position in this list. Shifts any * subsequent elements to the left (subtracts one from their indices). * Returns the element that was removed from the list. * * @param index the index of the element to be removed * @return the element previously at the specified position * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { checkElementIndex(index);//校验索引是否正常 return unlink(node(index)); }
-
checkElementIndex(index);メソッドを見てみましょう。
private void checkElementIndex(int index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); //如果isPositionIndex返回的是true,再取非,则不执行if条件语句,证明索引没问题 //如果isPositionIndex返回的是false,再取非,则执行if条件语句,抛出异常 }
-
入ってisElementIndex(index)を見てください
/** * Tells if the argument is the index of an existing element. */ private boolean isElementIndex(int index) { return index >= 0 && index < size;//注意这里的是索引要小于元素的个数,不能取等于,因为索引的个数是要比元素的个数少一个数的 }
-
インデックスの検証に問題がない場合は、ノード方式もあるアンリンク方式に依存します。
public E remove(int index) { checkElementIndex(index);//校验索引是否正常 return unlink(node(index)); }
-
最初にノード法を見てください
/** * Returns the (non-null) Node at the specified element index. */ Node<E> node(int index) { // assert isElementIndex(index); if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }
-
ノードの概略図
-
次に、リンク解除メソッドに戻ります。インデックス2のノードを削除する、つまり、アドレスが33のノードを削除するとします。
/** * Unlinks non-null node x. */ E unlink(Node<E> x) { // assert x != null; final E element = x.item;//就是那个被删除的节点返回回去 final Node<E> next = x.next; final Node<E> prev = x.prev; if (prev == null) { //删除的是头节点才会用到 first = next; } else { //假设我们现在删除的是索引为2的节点 prev.next = next; x.prev = null; } if (next == null) { //删除的是最后一个节点,显然现在不是,我们走else last = prev; } else { next.prev = prev; x.next = null; } x.item = null;//把33节点制为空, size--;//元素被删掉一个,被减一个 modCount++; return element;//就是返回那个被删除的节点 }
-
unlinkメソッド、つまり指定された要素を削除するための重要なメソッドは、削除するノードの両側のノードを切断する方法を見つけて、両側のノードを参照することです。回路図:
-