1. // 获取第一个元素
    2. public E getFirst() {
    3. final Node<E> f = first;
    4. if (f == null)
    5. throw new NoSuchElementException();
    6. return f.item;
    7. }
    1. // 获取最后一个元素
    2. public E getLast() {
    3. final Node<E> l = last;
    4. if (l == null)
    5. throw new NoSuchElementException();
    6. return l.item;
    7. }
    1. public E get(int index) {
    2. checkElementIndex(index);
    3. return node(index).item;
    4. }
    5. Node<E> node(int index) {
    6. // assert isElementIndex(index);
    7. if (index < (size >> 1)) { // 先判断index在左半部分还是右半部分,然后遍历
    8. Node<E> x = first;
    9. for (int i = 0; i < index; i++)
    10. x = x.next;
    11. return x;
    12. } else {
    13. Node<E> x = last;
    14. for (int i = size - 1; i > index; i--)
    15. x = x.prev;
    16. return x;
    17. }
    18. }