LinkedList有两个构造方法
1.LinkedList()
LinkedList linkedList = new LinkedList();
分析:
/** * Constructs an empty list. */ public LinkedList() { }
//无参构造方法构造了一个空集合
//其中,first,last是节点对象Node
//该结点为LinkedList的内部类,其中item指向要存放的元素,next,prev为指向后结点和前结点的结点引用,添加的元素是保存在这个Node对象中。 private static class Node<E> { E item; Node<E> next; Node<E> prev; Node(Node<E> prev, E element, Node<E> next) { this.item = element; this.next = next; this.prev = prev; } }
//调用add(E e)方法,实际调用的是linkLast(e)
/** * Appends the specified element to the end of this list. * * <p>This method is equivalent to {@link #addLast}. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */ public boolean add(E e) { linkLast(e); return true; }
//该方法将元素添加到队列最后面
/** * Links e as last element. */ void linkLast(E e) { final Node<E> l = last; //last此时为null //新创建的结点对象newNode ,pre指向l = null,next=null final Node<E> newNode = new Node<>(l, e, null); last = newNode; //last指向newNode if (l == null) //if判断成立,first指向newNode first = newNode; else l.next = newNode; size++; modCount++; }
//该方法执行完成后,linkedList情况为
//到此,添加方法add(1)完成,继续添加元素,add(2)
/** * Links e as last element. */ void linkLast(E e) { final Node<E> l = last;//(1) final Node<E> newNode = new Node<>(l, e, null);//(2) last = newNode;//(3) if (l == null) //(4) first = newNode; else //(5) l.next = newNode; size++; modCount++; }
分析:(1)此时last为上一步添加1元素时创建的结点对象,
l指向last,该l将作为newNode的前结点
(2)final Node<E> newNode = new Node<>(l, e, null);
创建了新的结点对象,用来保存新添加的元素2
该newNode的pre指向l即指向last(前结点,存放元素1的结点),next=null,
(3)将last指向newNode
(4)此时,(4)步骤不符合,执行(5),将前结点的next指向新结点newNode
至此,形成双向列表,linkedList中的first指向第一个节点(存放元素1的结点),last指向最后一个结点(存放元素2的结点)。如下图所示:
//添加操作完成,继续添加逻辑以此类推。