容器-LinkedList获取元素的源码分析(十)
-
LinkedList获取元素
//获取元素 for (int i=0;i<list.size();i++){ System.out.println(list.get(i)); }
-
真正获取元素的方法是list.get(i);
-
Ctrl+鼠标左键点击get,
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,所以把成员变量的值返回回去了 }
-
还是我们刚才分析的node方法
/** * 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; } }
-
node的原理图:
-
-
然后看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的,是对的。