Container-LinkedList to obtain the source code analysis of elements (10)
-
LinkedList get elements
//获取元素 for (int i=0;i<list.size();i++){ System.out.println(list.get(i)); }
-
The method to actually get the element is list.get(i);
-
Ctrl+left mouse button and click get,
E get(int index);
-
Use Ctrl+Alt to select the LinkedList interface implementation class of the get method
/** * 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; }
-
We look at the checkElementIndex method
private void checkElementIndex(int index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
-
Look at the isElementIndex(index) method again
/** * Tells if the argument is the index of an existing element. */ private boolean isElementIndex(int index) { return index >= 0 && index < size;//这里跟之前的那个不同,索引要大于等于0,索引小于元素的个数,不能取等于,因为元素的个数时从1开始的,长度要比索引小一位的 }
-
Then go back and look at the method of the checkElementIndex method
private void checkElementIndex(int index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); //如果isPositionIndex返回的是true,再取非,则不执行if条件语句,证明索引没问题 //如果isPositionIndex返回的是false,再取非,则执行if条件语句,抛出异常 }
-
Then look back at the get(int index) method
public E get(int index) { //根据索引的位置返回元素的方法 checkElementIndex(index);//校验index是否合法//这个已经执行完 return node(index).item;//然后通过node方法完之后,又去调用item这个存放元素的成员变量,这个方法返回的是 E,所以把成员变量的值返回回去了 }
-
Or the node method we just analyzed
/** * 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; } }
-
Schematic diagram of node:
-
-
Then look at the get method, 33 is returned, and then 33.item, so that the element with address 33 is retrieved
```java public E get(int index) { //根据索引的位置返回元素的方法 checkElementIndex(index);//校验index是否合法//这个已经执行完 return node(index).item;//然后通过node方法完之后,又去调用item这个存放元素的成员变量,这个方法返回的是 E,所以把成员变量的值返回回去了 } ```
-
33.item, so the element with address 33 is fetched, and the index is 2, which is correct.