文章的内容基于JDK1.7进行分析,之因此选用这个版本,是由于1.8的有些类作了改动,增长了阅读的难度,虽然是1.7,可是对于1.8作了重大改动的内容,文章也会进行说明。java
LinkedList类是List接口的实现类,它是一个集合,能够根据索引来随机的访问集合中的元素,还实现了Deque接口,它仍是一个队列,能够被当成双端队列来使用。虽然LinkedList是一个List集合,可是它的实现方式和ArrayList是彻底不一样的,ArrayList的底层是经过一个动态的Object[]数组来实现的,而LinkedList的底层是经过链表来实现的,所以它的随机访问速度是比较差的,可是它的删除,插入操做会很快。node
java.lang.Object java.util.AbstractCollection<E> java.util.AbstractList<E> java.util.AbstractSequentialList<E> java.util.LinkedList<E>
Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, List<E>, Queue<E>
transient int size = 0; //LinkedList中存放的元素个数 transient Node<E> first; //头节点 transient Node<E> last; //尾节点
什么是链表
链表是由一系列非连续的节点组成的存储结构,简单分下类的话,链表又分为单向链表和双向链表,而单向/双向链表又能够分为循环链表和非循环链表,下面简单就这四种链表进行图解说明。数组
1.单向链表
单向链表就是经过每一个结点的指针指向下一个结点从而连接起来的结构,最后一个节点的next指向null。安全
2.单向循环链表
单向循环链表和单向列表的不一样是,最后一个节点的next不是指向null,而是指向head节点,造成一个“环”。数据结构
3.双向链表
从名字就能够看出,双向链表是包含两个指针的,pre指向前一个节点,next指向后一个节点,可是第一个节点head的pre指向null,最后一个节点的tail指向null。ide
4.双向循环链表
双向循环链表和双向链表的不一样在于,第一个节点的pre指向最后一个节点,最后一个节点的next指向第一个节点,也造成一个“环”。而LinkedList就是基于双向循环链表设计的。性能
LinkedList是经过双向链表去实现的,既然是链表实现那么它的随机访问效率比ArrayList要低,顺序访问的效率要比较的高。每一个节点都有一个前驱(以前前面节点的指针)和一个后继(指向后面节点的指针),效果以下图:this
public class LinkedList<E>extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable { transient int size = 0; //LinkedList中存放的元素个数 transient Node<E> first; //头节点 transient Node<E> last; //尾节点 //构造方法,建立一个空的列表 public LinkedList() { } //将一个指定的集合添加到LinkedList中,先完成初始化,在调用添加操做 public LinkedList(Collection<? extends E> c) { this(); addAll(c); } //插入头节点 private void linkFirst(E e) { final Node<E> f = first; //将头节点赋值给f节点 //new 一个新的节点,此节点的data = e , pre = null , next - > f final Node<E> newNode = new Node<>(null, e, f); first = newNode; //将新建立的节点地址复制给first if (f == null) //f == null,表示此时LinkedList为空 last = newNode; //将新建立的节点赋值给last else f.prev = newNode; //不然f.前驱指向newNode size++; modCount++; } //插入尾节点 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++; } //在succ节点前插入e节点,并修改各个节点之间的前驱后继 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++; } //删除头节点 private E unlinkFirst(Node<E> f) { // assert f == first && f != null; final E element = f.item; final Node<E> next = f.next; f.item = null; f.next = null; // help GC first = next; if (next == null) last = null; else next.prev = null; size--; modCount++; return element; } //删除尾节点 private E unlinkLast(Node<E> l) { // assert l == last && l != null; final E element = l.item; final Node<E> prev = l.prev; l.item = null; l.prev = null; // help GC last = prev; if (prev == null) first = null; else prev.next = null; size--; modCount++; return element; } //删除指定节点 E unlink(Node<E> x) { // assert x != null; final E element = x.item; final Node<E> next = x.next; //获取指定节点的前驱 final Node<E> prev = x.prev; //获取指定节点的后继 if (prev == null) { first = next; //若是前驱为null, 说明此节点为头节点 } else { prev.next = next; //前驱结点的后继节点指向当前节点的后继节点 x.prev = null; //当前节点的前驱置空 } if (next == null) { //若是当前节点的后继节点为null ,说明此节点为尾节点 last = prev; } else { next.prev = prev; //当前节点的后继节点的前驱指向当前节点的前驱节点 x.next = null; //当前节点的后继置空 } x.item = null; //当前节点的元素设置为null ,等待垃圾回收 size--; modCount++; return element; } //获取LinkedList中的第一个节点信息 public E getFirst() { final Node<E> f = first; if (f == null) throw new NoSuchElementException(); return f.item; } //获取LinkedList中的最后一个节点信息 public E getLast() { final Node<E> l = last; if (l == null) throw new NoSuchElementException(); return l.item; } //删除头节点 public E removeFirst() { final Node<E> f = first; if (f == null) throw new NoSuchElementException(); return unlinkFirst(f); } //删除尾节点 public E removeLast() { final Node<E> l = last; if (l == null) throw new NoSuchElementException(); return unlinkLast(l); } //将添加的元素设置为LinkedList的头节点 public void addFirst(E e) { linkFirst(e); } //将添加的元素设置为LinkedList的尾节点 public void addLast(E e) { linkLast(e); } //判断LinkedList是否包含指定的元素 public boolean contains(Object o) { return indexOf(o) != -1; } //返回List中元素的数量 public int size() { return size; } //在LinkedList的尾部添加元素 public boolean add(E e) { linkLast(e); return true; } //删除指定的元素 public boolean remove(Object o) { if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); return true; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; } //将集合中的元素添加到List中 public boolean addAll(Collection<? extends E> c) { return addAll(size, c); } //将集合中的元素所有插入到List中,并从指定的位置开始 public boolean addAll(int index, Collection<? extends E> c) { checkPositionIndex(index); Object[] a = c.toArray(); //将集合转化为数组 int numNew = a.length; //获取集合中元素的数量 if (numNew == 0) //集合中没有元素,返回false return false; Node<E> pred, succ; if (index == size) { succ = null; pred = last; } else { succ = node(index); //获取位置为index的结点元素,并赋值给succ pred = succ.prev; } for (Object o : a) { //遍历数组进行插入操做。修改节点的前驱后继 @SuppressWarnings("unchecked") E e = (E) o; Node<E> newNode = new Node<>(pred, e, null); if (pred == null) first = newNode; else pred.next = newNode; pred = newNode; } if (succ == null) { last = pred; } else { pred.next = succ; succ.prev = pred; } size += numNew; modCount++; return true; } //删除List中全部的元素 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++; } //获取指定位置的元素 public E get(int index) { checkElementIndex(index); return node(index).item; } //将节点防止在指定的位置 public E set(int index, E element) { checkElementIndex(index); Node<E> x = node(index); E oldVal = x.item; x.item = element; return oldVal; } //将节点放置在指定的位置 public void add(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); } //删除指定位置的元素 public E remove(int index) { checkElementIndex(index); return unlink(node(index)); } //判断索引是否合法 private boolean isElementIndex(int index) { return index >= 0 && index < size; } //判断位置是否合法 private boolean isPositionIndex(int index) { return index >= 0 && index <= size; } //索引溢出信息 private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } //检查节点是否合法 private void checkElementIndex(int index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } //检查位置是否合法 private void checkPositionIndex(int index) { if (!isPositionIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } //返回指定位置的节点信息 //LinkedList没法随机访问,只能经过遍历的方式找到相应的节点 //为了提升效率,当前位置首先和元素数量的中间位置开始判断,小于中间位置, //从头节点开始遍历,大于中间位置从尾节点开始遍历 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 int indexOf(Object o) { int index = 0; if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) return index; index++; } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) return index; index++; } } return -1; } //返回最后一次出现元素的位置 public int lastIndexOf(Object o) { int index = size; if (o == null) { for (Node<E> x = last; x != null; x = x.prev) { index--; if (x.item == null) return index; } } else { for (Node<E> x = last; x != null; x = x.prev) { index--; if (o.equals(x.item)) return index; } } return -1; } //弹出第一个元素的值 public E peek() { final Node<E> f = first; return (f == null) ? null : f.item; } //获取第一个元素 public E element() { return getFirst(); } //弹出第一元素,并删除 public E poll() { final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); } //删除第一个元素 public E remove() { return removeFirst(); } //添加到尾部 public boolean offer(E e) { return add(e); } //添加到头部 public boolean offerFirst(E e) { addFirst(e); return true; } //插入到最后一个元素 public boolean offerLast(E e) { addLast(e); return true; } //队列操做 //尝试弹出第一个元素,可是不删除元素 public E peekFirst() { final Node<E> f = first; return (f == null) ? null : f.item; } //队列操做 //尝试弹出最后一个元素,不删除 public E peekLast() { final Node<E> l = last; return (l == null) ? null : l.item; } //弹出第一个元素,并删除 public E pollFirst() { final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); } //弹出最后一个元素,并删除 public E pollLast() { final Node<E> l = last; return (l == null) ? null : unlinkLast(l); } //如队列,添加到头部 public void push(E e) { addFirst(e); } //出队列删除第一个节点 public E pop() { return removeFirst(); } //删除指定元素第一次出现的位置 public boolean removeFirstOccurrence(Object o) { return remove(o); } //删除指定元素最后一次出现的位置 public boolean removeLastOccurrence(Object o) { if (o == null) { for (Node<E> x = last; x != null; x = x.prev) { if (x.item == null) { unlink(x); return true; } } } else { for (Node<E> x = last; x != null; x = x.prev) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; } //遍历方法 public ListIterator<E> listIterator(int index) { checkPositionIndex(index); return new ListItr(index); } //内部类,实现ListIterator接口 private class ListItr implements ListIterator<E> { private Node<E> lastReturned = null; private Node<E> next; private int nextIndex; private int expectedModCount = modCount; ListItr(int index) { // assert isPositionIndex(index); next = (index == size) ? null : node(index); nextIndex = index; } public boolean hasNext() { return nextIndex < size; } public E next() { checkForComodification(); if (!hasNext()) throw new NoSuchElementException(); lastReturned = next; next = next.next; nextIndex++; return lastReturned.item; } public boolean hasPrevious() { return nextIndex > 0; } public E previous() { checkForComodification(); if (!hasPrevious()) throw new NoSuchElementException(); lastReturned = next = (next == null) ? last : next.prev; nextIndex--; return lastReturned.item; } public int nextIndex() { return nextIndex; } public int previousIndex() { return nextIndex - 1; } public void remove() { checkForComodification(); if (lastReturned == null) throw new IllegalStateException(); Node<E> lastNext = lastReturned.next; unlink(lastReturned); if (next == lastReturned) next = lastNext; else nextIndex--; lastReturned = null; expectedModCount++; } public void set(E e) { if (lastReturned == null) throw new IllegalStateException(); checkForComodification(); lastReturned.item = e; } public void add(E e) { checkForComodification(); lastReturned = null; if (next == null) linkLast(e); else linkBefore(e, next); nextIndex++; expectedModCount++; } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } //静态内部类,建立节点 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; } } /** * @since 1.6 */ public Iterator<E> descendingIterator() { return new DescendingIterator(); } /** * Adapter to provide descending iterators via ListItr.previous */ private class DescendingIterator implements Iterator<E> { private final ListItr itr = new ListItr(size()); public boolean hasNext() { return itr.hasPrevious(); } public E next() { return itr.previous(); } public void remove() { itr.remove(); } } @SuppressWarnings("unchecked") private LinkedList<E> superClone() { try { return (LinkedList<E>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** * Returns a shallow copy of this {@code LinkedList}. (The elements * themselves are not cloned.) * * @return a shallow copy of this {@code LinkedList} instance */ public Object clone() { LinkedList<E> clone = superClone(); // Put clone into "virgin" state clone.first = clone.last = null; clone.size = 0; clone.modCount = 0; // Initialize clone with our elements for (Node<E> x = first; x != null; x = x.next) clone.add(x.item); return clone; } 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; } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) a = (T[])java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size); int i = 0; Object[] result = a; for (Node<E> x = first; x != null; x = x.next) result[i++] = x.item; if (a.length > size) a[size] = null; return a; } private static final long serialVersionUID = 876323262645176354L; //将对象写入到输出流中 private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out any hidden serialization magic s.defaultWriteObject(); // Write out size s.writeInt(size); // Write out all elements in the proper order. for (Node<E> x = first; x != null; x = x.next) s.writeObject(x.item); } //从输入流中将对象读出 @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in any hidden serialization magic s.defaultReadObject(); // Read in size int size = s.readInt(); // Read in all elements in the proper order. for (int i = 0; i < size; i++) linkLast((E)s.readObject()); } }
LinkedList() LinkedList(Collection<? extends E> c)
LinkedList没有长度的概念,因此不存在容量不足的问题,所以不须要提供初始化大小的构造方法,所以值提供了两个方法,一个是无参构造方法,初始一个LinkedList对象,和将指定的集合元素转化为LinkedList构造方法。spa
public boolean add(E e) { linkLast(e); return true; } 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++; }
添加方法默认是添加到LinkedList的尾部,首先将last指定的节点赋值给l节点,而后新建节点newNode ,此节点的前驱指向l节点,data = e , next = null , 并将新节点赋值给last节点,它成为了最后一个节点,根据当前List是否为空作出相应的操做。若不为空将l的后继指针修改成newNodw。 size +1 , modCount+1线程
public boolean remove(Object o) { if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); return true; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; }
删除方法,先循环遍历列表,找到item == o 的节点,在调用unlink()方法删除