List list = Collections.synchronizedList(new LinkedList(...))
LinkedList是一个链表,须要一个node类做为节点,所以他在内部构建了一个静态内部类。java
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; } }
静态内部类,该类不能直接访问LinkedLIst的非静态成员(属性和方法),由于Java的约束:静态方法不能直接访问非静态的成员。node
往==链表尾部==添加元素,boolean修饰,老是返回true数组
public boolean add(E e) { linkLast(e); return true; }
再看linkLast(e)方法安全
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++; }
若是l为空,则表示链表为空,插入的元素做为列表的第一个元素。
last是一个全局变量源码分析
transient Node<E> last;
而后相应的size也增长。size也是一个全局变量this
transient int size = 0;
这样的话就能够写个获取size的方法,因此的size的方法为线程
public int size() { return size; }
public E get(int index) { checkElementIndex(index); return node(index).item; }
==checkElementIndex(index)== 判断寻找的索引是否越界,若是越界则抛出异常。
==node(index).item== 经过方法取得nod对象,而后取得item的值。code
Node<E> node(int index) { // assert isElementIndex(index); if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }
这里经过位运算找出寻找范围的中间值,若是小于中间值,则出链头开始寻找,不然从链尾往回寻找。值得借鉴。对象
将列表转成数组的一个桥梁方法继承
public Object[] toArray() { Object[] result = new Object[size]; int i = 0; for (Node<E> x = first; x != null; x = x.next) result[i++] = x.item; return result; }
此调用返回后,列表将为空
public void clear() { // Clearing all of the links between nodes is "unnecessary", but: // - helps a generational GC if the discarded nodes inhabit // more than one generation // - is sure to free memory even if there is a reachable Iterator for (Node<E> x = first; x != null; ) { Node<E> next = x.next; x.item = null; x.next = null; x.prev = null; x = next; } first = last = null; size = 0; modCount++; }
能够利用该方法清空list列表,达到list屡次复用的目的,减小内存花销