用途与特色
可用于存储有序数据,底层使用链表形式进行数据存储。 该集合理论上只要内存能够存放数据,就能够一直添加,是无限扩容的。node
实现算法算法
底层使用Node的自定义对象进行存储,该对象中包含当前存储的数item、上一个节点prev、和下一个节点next 这三个属性来实现。但该链表是非环形,第一个first的prev为null,最后一个last的next为null,这样就造成了一下非闭环手拉手的效果。安全
LinkedList有3个主要属性size、first、last。线程
添加code
添加与删除的操做逻辑基本相同,再也不赘述。对象
/** * Links e as first element. */ private void linkFirst(E e) { final Node<E> f = first; final Node<E> newNode = new Node<>(null, e, f); first = newNode; if (f == null) last = newNode; else f.prev = newNode; size++; modCount++; } /** * Links e as last element. */ 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++; } /** * Inserts element e before non-null Node succ. */ void linkBefore(E e, Node<E> succ) { // assert succ != null; final Node<E> pred = succ.prev; final Node<E> newNode = new Node<>(pred, e, succ); succ.prev = newNode; if (pred == null) first = newNode; else pred.next = newNode; size++; modCount++; }
查找 blog
/** * Returns the (non-null) Node at the specified element index. */ Node<E> node(int index) { // assert isElementIndex(index); //根据传入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; } }
扩容机制内存
扩容时机:每次添加、删除都在扩容ci
是否线程安全,为何?element
非线程安全,由于在源码中未对数据的添加、删除、读取等作锁操做
根据jdk1.8版本源码解读