博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jdk1.8.0_45源码解读——LinkedList的实现
阅读量:4589 次
发布时间:2019-06-09

本文共 18044 字,大约阅读时间需要 60 分钟。

jdk1.8.0_45源码解读——LinkedList的实现

一、LinkedList概述

  LinkedList是List和Deque接口的双向链表的实现。实现了所有可选列表操作,并允许包括null值

    LinkedList既然是通过双向链表去实现的,那么它可以被当作堆栈、队列或双端队列进行操作。并且其顺序访问非常高效,而随机访问效率比较低

  注意,此实现不是同步的。 如果多个线程同时访问一个LinkedList实例,而其中至少一个线程从结构上修改了列表,那么它必须保持外部同步。这通常是通过同步那些用来封装列表的 对象来实现的。但如果没有这样的对象存在,则该列表需要运用{@link Collections#synchronizedList Collections.synchronizedList}来进行“包装”,该方法最好是在创建列表对象时完成,为了避免对列表进行突发的非同步操作。

List list = Collections.synchronizedList(new LinkedList(...));

  类中的iterator()方法和listIterator()方法返回的iterators迭代器是fail-fast的:当某一个线程A通过iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了;那么线程A访问集合时,就会抛出ConcurrentModificationException异常,产生fail-fast事件。

 

二、LinkedList源码解析

1.节点Node结构

private static class Node
{ E item; // 当前节点所包含的值 Node
next; //下一个节点 Node
prev; //上一个节点 Node(Node
prev, E element, Node
next) { this.item = element; this.next = next; this.prev = prev; } }

 

2. LinkedList类结构

//通过LinkedList实现的接口可知,其支持队列操作,双向列表操作,能被克隆,支持序列化public class LinkedList
extends AbstractSequentialList
implements List
, Deque
, Cloneable, java.io.Serializable{ // LinkedList的大小(指其所含的元素个数) transient int size = 0; /** * 指向第一个节点 * 不变的: (first == null && last == null) || * (first.prev == null && first.item != null) */ transient Node
first; /** * 指向最后一个节点 * 不变的: (first == null && last == null) || * (last.next == null && last.item != null) */ transient Node
last; ......}
View Code

LinkedList包含了三个重要的对象first、last 和 size。

(1) first双向链表的表头,它是双向链表节点所对应的类Node的实例

(2) last双向链表的最后一个元素,它是双向链表节点所对应的类Node的实例

(3) size 是双向链表中节点的个数。

 

3. 构造函数

LinkedList提供了两种种方式的构造器,构造一个空列表、以及构造一个包含指定collection的元素的列表,这些元素按照该collection的迭代器返回的顺序排列的。

//构建一个空列表    public LinkedList() {    }    /**     * 构造一个包含指定collection的元素的列表,这些元素按照该collection的迭代器返回的顺序排列的     * @param  c 包含用于去构造LinkedList的元素的collection     * @throws NullPointerException 如果指定的collection为空     */    //构建一个包含指定集合c的列表    public LinkedList(Collection
c) { this(); addAll(c); }
View Code

 

4. 添加元素

LinkedList提供了头插入addFirst(E e)尾插入addLast(E e)、add(E e)、addAll(Collection<? extends E> c)、addAll(int index, Collection<? extends E> c)、add(int index, E element)这些添加元素的方法。

//头插入,在列表首部插入节点值e    public void addFirst(E e) {        linkFirst(e);    }    //头插入,即将节点值为e的节点设置为链表首节点    private void linkFirst(E e) {        final Node
f = first; //构建一个prev值为null,节点值为e,next值为f的新节点newNode final Node
newNode = new Node<>(null, e, f); //将newNode作为首节点 first = newNode; //如果原首节点为null,即原链表为null,则链表尾节点也设置为newNode if (f == null) last = newNode; else //否则,原首节点的prev设置为newNode f.prev = newNode; size++; modCount++; } //尾插入,在列表尾部插入节点值e,该方法等价于add() public void addLast(E e) { linkLast(e); } //尾插入,在列表尾部插入节点值e public boolean add(E e) { linkLast(e); return true; } //尾插入,即将节点值为e的节点设置为链表的尾节点 void linkLast(E e) { final Node
l = last; //构建一个prev值为l,节点值为e,next值为null的新节点newNode final Node
newNode = new Node<>(l, e, null); //将newNode作为尾节点 last = newNode; //如果原尾节点为null,即原链表为null,则链表首节点也设置为newNode if (l == null) first = newNode; else //否则,原尾节点的next设置为newNode l.next = newNode; size++; modCount++; } //中间插入,在非空节点succ之前插入节点值e void linkBefore(E e, Node
succ) { // assert succ != null; final Node
pred = succ.prev; //构建一个prev值为succ.prev,节点值为e,next值为succ的新节点newNode final Node
newNode = new Node<>(pred, e, succ); //设置newNode为succ的前节点 succ.prev = newNode; //如果succ.prev为null,即如果succ为首节点,则将newNode设置为首节点 if (pred == null) first = newNode; else //如果succ不是首节点 pred.next = newNode; size++; modCount++; } /** * 按照指定collection的迭代器所返回的元素顺序,将该collection中的所有元素添加到此链表的尾部 * 如果指定的集合添加到链表的尾部的过程中,集合被修改,则该插入过程的后果是不确定的。 * 一般这种情况发生在指定的集合为该链表的一部分,且其非空。 * @throws NullPointerException 指定集合为null */ public boolean addAll(Collection
c) { return addAll(size, c); } //从指定的位置开始,将指定collection中的所有元素插入到此链表中,新元素的顺序为指定collection的迭代器所返回的元素顺序 public boolean addAll(int index, Collection
c) { checkPositionIndex(index); //index >= 0 && index <= size Object[] a = c.toArray(); int numNew = a.length; if (numNew == 0) return false; Node
pred, succ; //succ指向当前需要插入节点的位置,pred指向其前一个节点 if (index == size) { //说明在列表尾部插入集合元素 succ = null; pred = last; } else { succ = node(index); //得到索引index所对应的节点 pred = succ.prev; } //指定collection中的所有元素依次插入到此链表中指定位置的过程 for (Object o : a) { @SuppressWarnings("unchecked") E e = (E) o; //将元素值e,前继节点pred“封装”为一个新节点newNode Node
newNode = new Node<>(pred, e, null); if (pred == null) //如果原链表为null,则新插入的节点作为链表首节点 first = newNode; else pred.next = newNode; pred = newNode; //pred指针向后移动,指向下一个需插入节点位置的前一个节点 } //集合元素插入完成后,与原链表index位置后面的子链表链接起来 if (succ == null) { //说明之前是在列表尾部插入的集合元素 last = pred; //pred指向的是最后插入的那个节点 } else { pred.next = succ; succ.prev = pred; } size += numNew; modCount++; return true; } //将指定的元素(E element)插入到列表的指定位置(index) public void add(int index, E element) { checkPositionIndex(index); //index >= 0 && index <= size if (index == size) linkLast(element); //尾插入 else linkBefore(element, node(index)); //中间插入 }
View Code

 

5.删除元素

LinkedList提供了头删除removeFirst()、尾删除removeLast()、remove(int index)、remove(Object o)、clear()这些删除元素的方法。

//移除首节点,并返回该节点的元素值    public E removeFirst() {        final Node
f = first; if (f == null) throw new NoSuchElementException(); return unlinkFirst(f); } //删除非空的首节点f private E unlinkFirst(Node
f) { // assert f == first && f != null; final E element = f.item; final Node
next = f.next; f.item = null; f.next = null; // help GC first = next; //将原首节点的next节点设置为首节点 if (next == null) //如果原链表只有一个节点,即原首节点,删除后,链表为null last = null; else next.prev = null; size--; modCount++; return element; } //移除尾节点,并返回该节点的元素值 public E removeLast() { final Node
l = last; if (l == null) throw new NoSuchElementException(); return unlinkLast(l); } //删除非空的尾节点l private E unlinkLast(Node
l) { // assert l == last && l != null; final E element = l.item; final Node
prev = l.prev; l.item = null; l.prev = null; // help GC last = prev; //将原尾节点的prev节点设置为尾节点 if (prev == null) //如果原链表只有一个节点,则删除后,链表为null first = null; else prev.next = null; size--; modCount++; return element; } //移除此列表中指定位置上的元素 public E remove(int index) { checkElementIndex(index); //index >= 0 && index < size return unlink(node(index)); } //删除非空节点x E unlink(Node
x) { // assert x != null; final E element = x.item; final Node
next = x.next; final Node
prev = x.prev; if (prev == null) { //如果被删除节点为头节点 first = next; } else { prev.next = next; x.prev = null; } if (next == null) { //如果被删除节点为尾节点 last = prev; } else { next.prev = prev; x.next = null; } x.item = null; // help GC size--; modCount++; return element; } //移除列表中首次出现的指定元素(如果存在),LinkedList中允许存放重复的元素 public boolean remove(Object o) { //由于LinkedList中允许存放null,因此下面通过两种情况来分别处理 if (o == null) { for (Node
x = first; x != null; x = x.next) { //顺序访问 if (x.item == null) { unlink(x); return true; } } } else { for (Node
x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; } //清除列表中所有节点 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
x = first; x != null; ) { Node
next = x.next; x.item = null; x.next = null; x.prev = null; x = next; } first = last = null; size = 0; modCount++; }
View Code

 

6.修改元素

LinkedList提供了set(int index, E element)方法来修改指定索引上的值。

//替换指定索引位置节点的元素值,并返回旧值    public E set(int index, E element) {        checkElementIndex(index); //index >= 0 && index < size        Node
x = node(index); E oldVal = x.item; x.item = element; return oldVal; }
View Code

 

7.查找元素

LinkedList提供了getFirst()、getLast()、contains(Object o)、get(int index)、indexOf(Object o)、lastIndexOf(Object o)这些查找元素的方法。

//返回列表首节点元素值    public E getFirst() {        final Node
f = first; if (f == null) //如果首节点为null throw new NoSuchElementException(); return f.item; } //返回列表尾节点元素值 public E getLast() { final Node
l = last; if (l == null) //如果尾节点为null throw new NoSuchElementException(); return l.item; } //判断列表中是否包含有元素值o,返回true当列表中至少存在一个元素值e,使得(o==null?e==null:o.equals(e)) public boolean contains(Object o) { return indexOf(o) != -1; } //返回指定索引处的元素值 public E get(int index) { checkElementIndex(index); //index >= 0 && index < size return node(index).item; //node(index)返回指定索引位置index处的节点 } //返回指定索引位置的节点 Node
node(int index) { // assert isElementIndex(index); //折半思想,当index < size/2时,从列表首节点向后查找 if (index < (size >> 1)) { Node
x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { //当index >= size/2时,从列表尾节点向前查找 Node
x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } } //正向查找,返回LinkedList中元素值Object o第一次出现的位置,如果元素不存在,则返回-1 public int indexOf(Object o) { int index = 0; //由于LinkedList中允许存放null,因此下面通过两种情况来分别处理 if (o == null) { for (Node
x = first; x != null; x = x.next) { //顺序向后 if (x.item == null) return index; index++; } } else { for (Node
x = first; x != null; x = x.next) { if (o.equals(x.item)) return index; index++; } } return -1; } //逆向查找,返回LinkedList中元素值Object o最后一次出现的位置,如果元素不存在,则返回-1 public int lastIndexOf(Object o) { int index = size; //由于LinkedList中允许存放null,因此下面通过两种情况来分别处理 if (o == null) { for (Node
x = last; x != null; x = x.prev) { //逆向向前 index--; if (x.item == null) return index; } } else { for (Node
x = last; x != null; x = x.prev) { index--; if (o.equals(x.item)) return index; } } return -1; }
View Code

由LinkedList的类结构可以看出,LinkedList是AbstractSequentialList的子类。AbstractSequentialList 实现了get(int index)、set(int index, E element)、add(int index, E element) 和 remove(int index)这些随机访问的函数,那么LinkedList也实现了这些随机访问的接口。LinkedList具体是如何实现随机访问的?即,具体是如何定义index这个参数的?

在源码中,Node<E> node(int index)方法是得到索引index所指向的Node节点的。具体实现为:

//返回指定索引位置的节点    Node
node(int index) { // assert isElementIndex(index); //折半思想,当index < size/2时,从列表首节点向后查找 if (index < (size >> 1)) { Node
x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { //当index >= size/2时,从列表尾节点向前查找 Node
x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }

  该方法返回双向链表中指定位置处的节点,而链表中是没有下标索引的,要指定位置出的元素,就要遍历该链表,从源码的实现中,我们看到这里有一个加速动作。 源码中先将index与长度size的一半比较,如果index<size/2,就只从位置0往后遍历到位置index处,而如果 index>size/2,就只从位置size往前遍历到位置index处。这样可以减少一部分不必要的遍历。

 

8.其他public方法

clone()、toArray()、toArray(T[] a)

//返回此 LinkedList实例的浅拷贝    public Object clone() {        LinkedList
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
x = first; x != null; x = x.next) clone.add(x.item); return clone; } //返回一个包含LinkedList中所有元素值的数组 public Object[] toArray() { Object[] result = new Object[size]; int i = 0; for (Node
x = first; x != null; x = x.next) result[i++] = x.item; return result; } //如果给定的参数数组长度足够,则将ArrayList中所有元素按序存放于参数数组中,并返回 //如果给定的参数数组长度小于LinkedList的长度,则返回一个新分配的、长度等于LinkedList长度的、包含LinkedList中所有元素的新数组 @SuppressWarnings("unchecked") public
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
x = first; x != null; x = x.next) result[i++] = x.item; if (a.length > size) a[size] = null; return a; }
View Code

支持序列化的写入函数writeObject(java.io.ObjectOutputStream s)和读取函数readObject(java.io.ObjectInputStream s)

private static final long serialVersionUID = 876323262645176354L;    //序列化:将linkedList的“大小,所有的元素值”都写入到输出流中    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
x = first; x != null; x = x.next) s.writeObject(x.item); } //反序列化:先将LinkedList的“大小”读出,然后将“所有的元素值”读出 @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()); //以尾插入的方式 }
View Code

 

9.Queue操作

Queue操作提供了peek()、element()、poll()、remove()、offer(E e)这些方法。

//获取但不移除此队列的头;如果此队列为空,则返回 null    public E peek() {        final Node
f = first; return (f == null) ? null : f.item; } //获取但不移除此队列的头;如果此队列为空,则抛出NoSuchElementException异常 public E element() { return getFirst(); } //获取并移除此队列的头,如果此队列为空,则返回 null public E poll() { final Node
f = first; return (f == null) ? null : unlinkFirst(f); } //获取并移除此队列的头,如果此队列为空,则抛出NoSuchElementException异常 public E remove() { return removeFirst(); } //将指定的元素值(E e)插入此列表末尾 public boolean offer(E e) { return add(e); }
View Code

 

 10.Deque(双端队列)操作

Deque操作提供了offerFirst(E e)、offerLast(E e)、peekFirst()、peekLast()、pollFirst()、pollLast()、push(E e)、pop()、removeFirstOccurrence(Object o)、removeLastOccurrence(Object o)这些方法。

//获取但不移除此队列的头;如果此队列为空,则返回 null    public E peek() {        final Node
f = first; return (f == null) ? null : f.item; } //获取但不移除此队列的头;如果此队列为空,则抛出NoSuchElementException异常 public E element() { return getFirst(); } //获取并移除此队列的头,如果此队列为空,则返回 null public E poll() { final Node
f = first; return (f == null) ? null : unlinkFirst(f); } //获取并移除此队列的头,如果此队列为空,则抛出NoSuchElementException异常 public E remove() { return removeFirst(); } //将指定的元素值(E e)插入此列表末尾 public boolean offer(E e) { return add(e); } // Deque operations //将指定的元素插入此双端队列的开头 public boolean offerFirst(E e) { addFirst(e); return true; } //将指定的元素插入此双端队列的末尾 public boolean offerLast(E e) { addLast(e); return true; } //获取,但不移除此双端队列的第一个元素;如果此双端队列为空,则返回 null public E peekFirst() { final Node
f = first; return (f == null) ? null : f.item; } //获取,但不移除此双端队列的最后一个元素;如果此双端队列为空,则返回 null public E peekLast() { final Node
l = last; return (l == null) ? null : l.item; } //获取并移除此双端队列的第一个元素;如果此双端队列为空,则返回 null public E pollFirst() { final Node
f = first; return (f == null) ? null : unlinkFirst(f); } //获取并移除此双端队列的最后一个元素;如果此双端队列为空,则返回 null public E pollLast() { final Node
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) { //由于LinkedList中允许存放null,因此下面通过两种情况来分别处理 if (o == null) { for (Node
x = last; x != null; x = x.prev) { //逆向向前 if (x.item == null) { unlink(x); return true; } } } else { for (Node
x = last; x != null; x = x.prev) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; }
View Code

 

11. Fail-Fast机制

LinkedList也采用了快速失败的机制,通过记录modCount参数来实现。在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。

 

三、常用的LinkedList的遍历方式

LinkedList不提倡运用随机访问的方式进行元素遍历。

1)通过迭代器Iterator遍历:

Iterator iter = list.iterator();    while (iter.hasNext())    {        System.out.println(iter.next());    }

2)通过迭代器ListIterator遍历:

  ListIterator
lIter = list.listIterator();  //顺向遍历  while(lIter.hasNext()){   System.out.println(lIter.next());  }  //逆向遍历   while(lIter.hasPrevious()){   System.out.println(lIter.previous());   }

3)foreach循环遍历

for(String str:list)    {        System.out.println(str);    }

 

四、LinkedList的运用

 LinkedList实现堆栈:

 

【感谢】

转载于:https://www.cnblogs.com/CherishFX/p/4734490.html

你可能感兴趣的文章
c# 使用泛型集合List<T>
查看>>
c# Dictionary<K,V>
查看>>
c# Unicode
查看>>
c# String类
查看>>
c# 搜索字符串
查看>>
c# 比较字符串
查看>>
c# StringBuilder类
查看>>
c# 格式化数据String.Format
查看>>
c# 日期和时间System.DateTime
查看>>
c# 字符串修改
查看>>
c# 正则表达式
查看>>
c# Regex类
查看>>
c# Match类
查看>>
c# MatchCollection类
查看>>
c# Group类
查看>>
c# FileStream 类构造函数
查看>>
c# MemoryStream 类
查看>>
c# BufferedStream 类
查看>>
c# CryptoStream 类
查看>>
c# 读取文本文件
查看>>