• 双向链表、无长度限制,内部保存了链表的头节点和尾节点。
  • 查找首尾节点快,查找中间节点慢,整体比ArrayList慢
  • 首尾添加元素比中间添加元素快,整体比ArrayList快
  • 删除首尾元素比中间元素快,整体比ArrayList快

    add(E e)

    添加到尾节点
    1. //往队尾添加元素
    2. public boolean add(E e) {
    3. linkLast(e);
    4. return true;
    5. }
    1. void linkLast(E e) {
    2. //取出队尾元素
    3. final Node<E> l = last;
    4. //构造新节点,新节点的pre为尾节点,next为null
    5. final Node<E> newNode = new Node<>(l, e, null);
    6. //新节点作为尾节点
    7. last = newNode;
    8. //如果尾节点为空,把当前节点作为尾节点
    9. //如果不为空,把为节点的next指向新节点
    10. if (l == null)
    11. first = newNode;
    12. else
    13. l.next = newNode;
    14. size++;
    15. modCount++;
    16. }

    add(int index,E e)

    //在index位置之前添加元素element
    public void add(int index, E element) {
      checkPositionIndex(index);
      //判断是否为往为节点插入
      if (index == size)
          linkLast(element);
      else
          //先找到要插入位置的元素,再执行插入
          linkBefore(element, node(index));
    }
    

    具体请见源代码