要素のソースコード分析を取得するためのContainer-LinkedList(10)
-
LinkedListは要素を取得します
//获取元素 for (int i=0;i<list.size();i++){ System.out.println(list.get(i)); }
-
実際に要素を取得する方法はlist.get(i);です。
-
Ctrlキーを押しながらマウスの左ボタンを押して[取得]をクリックし、
E get(int index);
-
Ctrl + Altを使用して、getメソッドのLinkedListインターフェース実装クラスを選択します
/** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { //根据索引的位置返回元素的方法 checkElementIndex(index);//校验index是否合法 return node(index).item; }
-
checkElementIndexメソッドを見てみましょう
private void checkElementIndex(int index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
-
isElementIndex(index)メソッドをもう一度見てください
/** * Tells if the argument is the index of an existing element. */ private boolean isElementIndex(int index) { return index >= 0 && index < size;//这里跟之前的那个不同,索引要大于等于0,索引小于元素的个数,不能取等于,因为元素的个数时从1开始的,长度要比索引小一位的 }
-
次に戻って、checkElementIndexメソッドのメソッドを確認します。
private void checkElementIndex(int index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); //如果isPositionIndex返回的是true,再取非,则不执行if条件语句,证明索引没问题 //如果isPositionIndex返回的是false,再取非,则执行if条件语句,抛出异常 }
-
次に、get(int index)メソッドを振り返ります
public E get(int index) { //根据索引的位置返回元素的方法 checkElementIndex(index);//校验index是否合法//这个已经执行完 return node(index).item;//然后通过node方法完之后,又去调用item这个存放元素的成员变量,这个方法返回的是 E,所以把成员变量的值返回回去了 }
-
または、分析したノード法
/** * 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; } }
-
ノードの概略図:
-
-
次に、getメソッドを見ると、33が返され、次に33.itemが返されるため、アドレス33の要素が取得されます。
```java public E get(int index) { //根据索引的位置返回元素的方法 checkElementIndex(index);//校验index是否合法//这个已经执行完 return node(index).item;//然后通过node方法完之后,又去调用item这个存放元素的成员变量,这个方法返回的是 E,所以把成员变量的值返回回去了 } ```
-
33.itemなので、アドレス33の要素がフェッチされ、インデックスは2です。これは正しいです。