博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LinkedList源码初探
阅读量:2740 次
发布时间:2019-05-13

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

准备:

LinkedList是基于链表(双向循环链表)结构的一种List,在分析LinkedList源码之前我们先看看链表

1、链表概念

链表是由一系列非连续的节点组成的存储结构,简单分下类的话,链表又分为单向链表和双向链表,而单向/双向链表又可以分为循环链表和非循环链表,下面简单就这四种链表进行图解说明。

1.1、单向链表

单向链表就是通过每个结点的指针指向下一个结点从而链接起来的结构,最后一个节点的next指向null。

单向链表.jpg

1.2、单向循环链表

单向循环链表和单向列表的不同是,最后一个节点的next不是指向null,而是指向head节点,形成一个“环”。

单向循环链表.jpg

1.3、双向链表

从名字就可以看出,双向链表是包含两个指针的,pre指向前一个节点,next指向后一个节点,但是第一个节点head的pre指向null,最后一个节点的tail指向null。

双向链表.jpg

1.4、双向循环链表

双向循环链表和双向链表的不同在于,第一个节点的pre指向最后一个节点,最后一个节点的next指向第一个节点,也形成一个“环”。而LinkedList就是基于双向循环链表设计的。

双向循环链表.jpg

更形象的解释下就是:双向循环链表就像一群小孩手牵手围成一个圈,第一个小孩的右手拉着第二个小孩的左手,第二个小孩的左手拉着第一个小孩的右手。。。最后一个小孩的右手拉着第一个小孩的左手。

附图:

timg.jpg

一 :结构关系

public class LinkedList
extends AbstractSequentialList
implements List
, Deque
, Cloneable, Serializable{

结构.png

结构图.png

 

可以看出LinkedList 继承AbstractSequentialList 抽象类,实现List,Deque,Cloneable,Serializable 几个接口,AbstractSequentialList 继承 AbstractList,是对其中方法的再抽象,其主要作用是最大限度地减少了实现受“连续访问”数据存储(如链接列表)支持的此接口所需的工作,简单说就是,如果需要快速的添加删除数据等,用AbstractSequentialList抽象类,若是需要快速随机的访问数据等用AbstractList抽象类(详细说明会在iterator 分析中进行解释)。

注意:

Deque 是一个双向队列,也就是既可以先入先出,又可以先入后出,再直白一点就是既可以在头部添加元素又在尾部添加元素,既可以在头部获取元素又可以在尾部获取元素。看下Deque的定义:

public interface Deque
extends Queue
{ void addFirst(E e); boolean offerFirst(E e); boolean offerLast(E e); E removeFirst(); E removeLast(); E pollFirst(); E pollLast(); E getFirst(); E getLast(); E peekFirst(); E peekLast(); boolean removeFirstOccurrence(Object o); boolean removeLastOccurrence(Object o); // *** Queue methods *** boolean add(E e); boolean offer(E e); E remove(); E poll(); E element(); E peek(); // *** Stack methods *** void push(E e); E pop(); // *** Collection methods *** boolean remove(Object o); boolean contains(Object o); public int size(); Iterator
iterator(); Iterator
descendingIterator();}

二 :介绍

(1):LinkedList是基于双向循环链表实现的,除了可以当做链表来操作外,它还可以当做栈、队列和双端队列来使用。

(2):是一种链表类型的数据结构,支持高效的插入和删除操作,同时也实现了Deque接口,使得LinkedList类也具有队列的特性。LinkedList类的底层实现的数据结构是一个双端的链表。
(3): 不是线程安全的
(4):LinkedList实现了Serializable接口,因此它支持序列化,能够通过序列化传输,实现了Cloneable接口,能被克隆。

三 :重要知识点

(1):重要属性

(2):LinkedList的创建:即构造器
(3):重点内部类以及重点方法
(4):线程安全与否以及解决方案

四 :源码浅析

4.1重要属性:

//集合长度    transient int size = 0;    //首节点    transient Node
first; //尾节点 transient Node
last;这里注意LinkedList的元素结构,是一个node元素,是一个双向链表,我们看看node的构成 // 双向链表的节点所对应的数据结构。 // 包含3部分:上一节点,下一节点,当前节点值。 private static class Node
{ E item;// 当前节点所包含的值 Node
next;// 下一个节点 Node
prev; // 上一个节点 /** * 链表节点的构造函数。 * 参数说明: * element —— 节点所包含的数据 * next —— 下一个节点 * previous —— 上一个节点 */ Node(Node
prev, E element, Node
next) { this.item = element; this.next = next; this.prev = prev; } }

注意上边的node源码,LinkedList类中有一个内部私有类Node,这个类就代表双端链表的节点Node。这个类有三个属性,分别是前驱节点,本节点的值,后继结点。

注意这个节点的初始化方法,给定三个参数,分别前驱节点,本节点的值,后继结点。这个方法将在LinkedList的实现中多次调用。

4.2创建一个LinkedList:

API提供了两种创建LinkedList的构造方法(1): public LinkedList()  //无参构造创建(2):public LinkedList(Collection
c)//带参构造创建

4.3向LinkedList中添加元素:

LinkedList的添加方法有好几个(1):public boolean add(E e) (1):public boolean addAll(Collection
c) (1):public void add(int index, E element)(1):public void addFirst(E e)(1):public void addLast(E e)这里我们主要分析add(E e),以下是源码: //追加节点(尾部添加) public boolean add(E e) { linkLast(e); return true; } //在链表尾部添加一个元素 void linkLast(E e) { final Node
l = last; final Node
newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }

t添加图解.jpg

增加元素的实现其实很简单,只要理解了双向链表的存储结构,掌握增加的核心逻辑就可以了。这里总结一下核心逻辑:1.将元素转换为链表节点,2.增加该节点的前后引用(即pre和next分别指向哪一个节点),3.前后节点对该节点的引用(前节点的next指向该节点,后节点的pre指向该节点)。其实就是前后变换的互相指向关系

4.4从LinkedList中移除元素:

同样LinkedList的删除方法也有好几个(1):public boolean remove(Object o)(2):public E remove() (3):public E remove(int index)(4):public E removeFirst()(5):public E removeLast()这里一样,我们重点看public E remove()     //删除并返回第一个节点  若LinkedList的大小为0,则抛出异常    public E remove() {        return removeFirst();    }    //移除首节点并返回该节点    public E removeFirst() {        final Node
f = first; if (f == null) throw new NoSuchElementException(); return unlinkFirst(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; if (next == null) last = null; else next.prev = null; size--;//容量-- modCount++; return element; }

上面对于链表增加元素总结了,一句话就是“改变前后的互相指向关系”,删除也是同样的道理,由于节点被删除,该节点的上一个节点和下一个节点互相拉一下小手就可以了,注意的是“互相”,不能一厢情愿。

4.5修改LinkedList中某个元素:

//设置index位置对应的节点的值为element     public E set(int index, E element) {        checkElementIndex(index);        Node
x = node(index); E oldVal = x.item; x.item = element; return oldVal; }

set方法看起来简单了很多,只要修改该节点上的元素就好了,但是不要忽略了这里的 node(index)方法,重点就是它。

4.5查询LinkedList中某个元素:

LinkedList提供了各种方式的get方法方便开发调用(1):public E get(int index)(2):public E getFirst() (3):public E getLast()主动看public E get(int index)索引获取源码:    // 返回LinkedList指定位置的元素     public E get(int index) {        checkElementIndex(index);//检查索引        return node(index).item;//注意,这里item才是真正的数据,Node并不是    }    //返回指定元素索引中的(非空)节点    Node
node(int index) { // assert isElementIndex(index); if (index < (size >> 1)) { Node
x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node
x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }

现在知道了,LinkedList是通过从header开始index计为0,然后一直往下遍历(next),直到到底index位置。为了优化查询效率,LinkedList采用了二分查找(这里说的二分只是简单的一次二分),判断index与size中间位置的距离,采取从header向后还是向前查找。

到这里我们明白,基于双向循环链表实现的LinkedList,通过索引Index的操作时低效的,index所对应的元素越靠近中间所费时间越长。而向链表两端插入和删除元素则是非常高效的(如果不是两端的话,都需要对链表进行遍历查找)。

4.6容量:

public int size() {        return size ;    }     public boolean isEmpty() {        return size() == 0;    }

4.6LinkedList实现的Deque双端队列 :

//将元素E添加到链表末尾    public boolean offer(E e) {        return add(e);    }    //删除并返回第一个节点  若LinkedList的大小为0,则返回null    public E poll() {        final Node
f = first; return (f == null) ? null : unlinkFirst(f); } //删除并返回第一个节点 public E pop() { return removeFirst(); } //返回第一个节点 若LinkedList的大小为0,则返回null public E peek() { final Node
f = first; return (f == null) ? null : f.item; } //获取首节点 public E getFirst() { final Node
f = first; if (f == null) throw new NoSuchElementException(); return f.item; } //将e插入到双向链表开头 public void push(E e) { addFirst(e); } //添加头节点 public void addFirst(E e) { linkFirst(e); }

4.6迭代元素:

如果仔细观察,你会发现在 LinkedList中是没有自己实现 iterator的,如果这样调用:

LinkedList
list = new LinkedList<>();Iterator
it = list.iterator();

你会发现它调用的是 AbstractSequentialList中的 iterator(),返回的还是 AbstractList 中的 listIterator(),而在 LinkedList中实现了自己的 listIterator,因此如果进行迭代,还是老老实实用 LinkedList中的 listIterator比较好。LinkedList中还提供了逆序的 Iterator—— DescendingIterator,实际上它也只是简单的对 ListIterator进行了封装:

public Iterator
iterator() { return listIterator(); } public ListIterator
listIterator() { return listIterator(0); } public ListIterator
listIterator(final int index) { rangeCheckForAdd(index); return new ListItr(index);//最终返回的是一个Listltr的迭代器 }

看看Listltr源码(是AbstractSequentialList的私有内部类)

private class ListItr extends Itr implements ListIterator
{ ListItr(int index) { cursor = index; } public boolean hasPrevious() { return cursor != 0; } public E previous() { checkForComodification(); try { int i = cursor - 1; E previous = get(i); lastRet = cursor = i; return previous; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } public int nextIndex() { return cursor; } public int previousIndex() { return cursor-1; } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.set(lastRet, e); expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; AbstractList.this.add(i, e); lastRet = -1; cursor = i + 1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } }

五 :线程安全问题

LinkedList和arrayList一样都是线程不安全的,如果在多线程程序中有多个线程访问LinkedList的话会出现抛出ConcurrentModificationException

final void checkForComodification() {        if (modCount != expectedModCount)        throw new ConcurrentModificationException();    }

代码中,modCount记录了LinkedList结构被修改的次数。Iterator初始化时,expectedModCount=modCount。任何通过Iterator修改LinkedList结构的行为都会同时更新expectedModCount和modCount,使这两个值相等。通过LinkedList对象修改其结构的方法只更新modCount。所以假设有两个线程A和B。A通过Iterator遍历并修改LinkedList,而B,与此同时,通过对象修改其结构,那么Iterator的相关方法就会抛出异常。这是相对容易发现的由线程竞争造成的错误。

测试代码:/** * ClassName: TestLinkedList * @author lvfang * @Desc: TODO * @date 2017-9-21 */public class TestLinkedList implements Runnable {        private LinkedList
list = null; public TestLinkedList(LinkedList
list){ this.list = list; } @Override public void run() { for(int i=0;i<10;i++) list.add(i); System.out.println(list.size()); } /** * LinkedList线程安全测试 * @param args */ public static void main(String[] args) { LinkedList
list = new LinkedList<>(); //启动5个线程,每个线程向集合中添加10条数据,最终应该是50 for (int i = 0; i < 5; i++) { new Thread(new TestLinkedList(list)).start(); } } }

解决方案

方案一:Collections类的同步list方法

List<String> linkedList = Collections.synchronizedList(new LinkedList<String>())

方案二:ConcurrentLinkedQueue代替linkedList

六 :总结(LinkedList和ArrayList的大致区别)

1、ArrayList继承于 AbstractList, LinkedList继承于 AbstractSequentialList;

2、ArrayList基于数组, LinkedList基于双向链表,对于随机访问, ArrayList比较占优势,LinkedList插入、删除元素比较快,如果只要调整指针的指向那么时间复杂度是O(1),但是如果针对特定位置需要遍历时,时间复杂度是O(n),也就是LinkedList在随机访问元素的话比较慢;
3、LinkedList没有实现自己的 Iterator,但是有 ListIterator和 DescendingIterator;
4、LinkedList需要更多的内存,因为 ArrayList的每个索引的位置是实际的数据,而 LinkedList中的每个节点中存储的是实际的数据和前后节点的位置;
5、ArrayList 和 LinkedList都是非同步的集合。
6、和ArrayList一样,LinkedList也是非线程安全的,只有在单线程下才可以使用。为了防止非同步访问,可以采用如下方式创建LinkedList:List list= Collections.synchronizedList(new LinkedList());
7、LinkedList基于双向链表实现,元素都可以为null。

 

转载地址:http://ylwad.baihongyu.com/

你可能感兴趣的文章
ORA-01950: no privileges on tablespace 解决方法
查看>>
IMP-00013: only a DBA can import a file exported by another DBA 问题及解决方案
查看>>
oracle创建用户ORA-01045:user lacks CREATE SESSION privilege;logon denied..的问题
查看>>
Oracle 用户对表空间配额quota说明
查看>>
oracle中exp,imp的使用详解
查看>>
oracle drop表空间
查看>>
好心态
查看>>
Web MVC
查看>>
java强行删除文件(针对进程正在使用的文件的删除)
查看>>
【OSGi】OSGi框架的三个层次
查看>>
ActionContext,ServletContext和ServletActionContext有什么区别?
查看>>
Struts2标签 %{ } %{# }详解
查看>>
Java集合----HashSet的实现原理
查看>>
HashMap实现原理分析
查看>>
${pageContext.request.contextPath} JSP取得绝对路径
查看>>
ztree显示
查看>>
JQUERY树型插件ZTREE和插件tmpl()
查看>>
zTree--jQuery快速学习笔记
查看>>
jQuery基础知识
查看>>
[原]红帽 Red Hat Linux相关产品iso镜像下载
查看>>