getFirst(),获取头部元素
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
直接返回first指针对应的内容即可。
peek(),获取头部元素
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
peek()其实和getFirst()是一样的。区别只是在为空时,peek直接返回null,而getFirst抛异常。
getLast,获取尾部元素
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
返回last指针对应的内容。
get(int index),根据下标获取元素
public E get(int index) {
checkElementIndex(index); //检查index是否合法
return node(index).item;
}
这里会调用node(index)找到对应的节点,这个方法上一节分析过。会比较index和size >> 1,如果在前半部分,就会从头部开始遍历;如果在后半部分,就会从尾部开始遍历。