如图在主方法中
在jdk源码中首先调用无参构造器,由注释构造一个空的列表
*1.先进入无参构造器中去 * public LinkedList() { } * 2.调用add方法前,先进行自动装箱的操作 * public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); } *3.在进入add方法中,进入linkLast(e); * public boolean add(E e) { linkLast(e); return true; } * 4.在linkLast(e)方法中,有由于first和last都为null对象, * 所以l = null,并创建一个对象把头和尾置为null;并且把first和last都 * 指向该对象;如图所示: * void linkLast(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; } * * 5.进入第二个添加也是先进行自动装箱,然后跳到 void linkLast(E e)方法中去 * l -> last也就是指向第一个添加的对象,再创建一个对象,final Node<E> newNode = new Node<>(l, e, null); * l传给了怕热,第二个对象的pre指向l * 把last指向第二个对象,那么last指向第一个对象的引用就没了,而第一个对象next * 指向第二个对象,这样就形成了双向链表,first指向第一个对象,而last指向最后的一个对象 如图所示: * void linkLast(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; } * * * */