LinkedList 实现了List接口和Deque接口 是一个 先进先出 双向链表结构 重点是first 和 last 看下元素类型 Node 有next prev 和 item(current) 实现链表
1 private static class Node<E> { 2 E item; 3 Node<E> next; 4 Node<E> prev; 5 6 Node(Node<E> prev, E element, Node<E> next) { 7 this.item = element; 8 this.next = next; 9 this.prev = prev; 10 } 11 }
查看add方法实现 可以知道LinkedList 插入很快 因为不会像ArrayList那样维护数组 add是追加到队列的last
1 void linkLast(E e) { 2 final Node<E> l = last; 3 final Node<E> newNode = new Node<>(l, e, null); 4 last = newNode; 5 if (l == null) 6 first = newNode; 7 else 8 l.next = newNode; 9 size++; 10 modCount++; 11 }
查看get方法实现 有一个判断 如果index < size/2 则从队列头循环 else从队列尾循环 可以发现 LinkedList的检索比较慢 因为会循环遍历
1 Node<E> node(int index) { 2 // assert isElementIndex(index); 3 4 if (index < (size >> 1)) { 5 Node<E> x = first; 6 for (int i = 0; i < index; i++) 7 x = x.next; 8 return x; 9 } else { 10 Node<E> x = last; 11 for (int i = size - 1; i > index; i--) 12 x = x.prev; 13 return x; 14 } 15 }
查看pop()方法实现 返回并remove first
1 /** 2 * Removes and returns the first element from this list. 3 * 4 * @return the first element from this list 5 * @throws NoSuchElementException if this list is empty 6 */ 7 public E removeFirst() { 8 final Node<E> f = first; 9 if (f == null) 10 throw new NoSuchElementException(); 11 return unlinkFirst(f); 12 }
其他方法查看源码..