LinkedList的源码分析

linkedlist也和arraylist一样实现了list接口,但是它执行插入和删除操作时比arraylist更加高效,因为它是基于链表的。基于链表也决定了它在随机访问方面要比arraylist逊色一点。
除此之外,linkedlist还提供了一些可以使其作为栈、队列、双端队列的方法。这些方法中有些彼此之间只是名称的区别,以使得这些名字在特定的上下文中显得更加的合适。
先看linkedlist类的定义。
1 public class linkedlist《e》
2 extends abstractsequentiallist《e》
3 implements list《e》, deque《e》, cloneable, java.io.serializable
linkedlist继承自abstractsequencelist、实现了list及deque接口。其实abstractsequencelist已经实现了list接口,这里标注出list只是更加清晰而已。abstractsequencelist提供了list接口骨干性的实现以减少实现list接口的复杂度。deque接口定义了双端队列的操作。
linkedlist中之定义了两个属性:
1 private transient entry《e》 header = new entry《e》(null, null, null);
2 private transient int size = 0;
size肯定就是linkedlist对象里面存储的元素个数了。linkedlist既然是基于链表实现的,那么这个header肯定就是链表的头结点了,entry就是节点对象了。一下是entry类的代码。
1 private static class entry《e》 {
2 e element;
3 entry《e》 next;
4 entry《e》 previous;
5
6 entry(e element, entry《e》 next, entry《e》 previous) {
7 this.element = element;
8 this.next = next;
9 this.previous = previous;
10 }
11 }
只定义了存储的元素、前一个元素、后一个元素,这就是双向链表的节点的定义,每个节点只知道自己的前一个节点和后一个节点。
来看linkedlist的构造方法。
1 public linkedlist() {
2 header.next = header.previous = header;
3 }
4 public linkedlist(collection《? extends e》 c) {
5 this();
6 addall(c);
7 }
linkedlist提供了两个构造方法。第一个构造方法不接受参数,只是将header节点的前一节点和后一节点都设置为自身(注意,这个是一个双向循环链表,如果不是循环链表,空链表的情况应该是header节点的前一节点和后一节点均为null),这样整个链表其实就只有header一个节点,用于表示一个空的链表。第二个构造方法接收一个collection参数c,调用第一个构造方法构造一个空的链表,之后通过addall将c中的元素全部添加到链表中。来看addall的内容。
1 public boolean addall(collection《? extends e》 c) {
2 return addall(size, c);
3 }
4 // index参数指定collection中插入的第一个元素的位置
5 public boolean addall(int index, collection《? extends e》 c) {
6 // 插入位置超过了链表的长度或小于0,报indexoutofboundsexception异常
7 if (index 《 0 || index 》 size)
8 throw new indexoutofboundsexception(“index: ”+index+
9 “, size: ”+size);
10 object[] a = c.toarray();
11 int numnew = a.length;
12 // 若需要插入的节点个数为0则返回false,表示没有插入元素
13 if (numnew==0)
14 return false;
15 modcount++;
16 // 保存index处的节点。插入位置如果是size,则在头结点前面插入,否则获取index处的节点
17 entry《e》 successor = (index==size ? header : entry(index));
18 // 获取前一个节点,插入时需要修改这个节点的next引用
19 entry《e》 predecessor = successor.previous;
20 // 按顺序将a数组中的第一个元素插入到index处,将之后的元素插在这个元素后面
21 for (int i=0; i《numnew; i++) {
22 // 结合entry的构造方法,这条语句是插入操作,相当于c语言中链表中插入节点并修改指针
23 entry《e》 e = new entry《e》((e)a[i], successor, predecessor);
24 // 插入节点后将前一节点的next指向当前节点,相当于修改前一节点的next指针
25 predecessor.next = e;
26 // 相当于c语言中成功插入元素后将指针向后移动一个位置以实现循环的功能
27 predecessor = e;
28 }
29 // 插入元素前index处的元素链接到插入的collection的最后一个节点
30 successor.previous = predecessor;
31 // 修改size
32 size += numnew;
33 return true;
34 }
构造方法中的调用了addall(collection《? extends e》 c)方法,而在addall(collection《? extends e》 c)方法中仅仅是将size当做index参数调用了addall(int index,collection《? extends e》 c)方法。
1 private entry《e》 entry(int index) {
2 if (index 《 0 || index 》= size)
3 throw new indexoutofboundsexception(“index: ”+index+
4 “, size: ”+size);
5 entry《e》 e = header;
6 // 根据这个判断决定从哪个方向遍历这个链表
7 if (index 《 (size 》》 1)) {
8 for (int i = 0; i 《= index; i++)
9 e = e.next;
10 } else {
11 // 可以通过header节点向前遍历,说明这个一个循环双向链表,header的previous指向链表的最后一个节点,这也验证了构造方法中对于header节点的前后节点均指向自己的解释
12 for (int i = size; i 》 index; i--)
13 e = e.previous;
14 }
15 return e;
16 }
结合上面代码中的注释及双向循环链表的知识,应该很容易理解linkedlist构造方法所涉及的内容。下面开始分析linkedlist的其他方法。
add(e e)
1 public boolean add(e e) {
2 addbefore(e, header);
3 return true;
4 }
从上面的代码可以看出,add(e e)方法只是调用了addbefore(e e,entry《e》 entry)方法,并且返回true。
addbefore(e e,entry《e》 entry)
1 private entry《e》 addbefore(e e, entry《e》 entry) {
2 entry《e》 newentry = new entry《e》(e, entry, entry.previous);
3 newentry.previous.next = newentry;
4 newentry.next.previous = newentry;
5 size++;
6 modcount++;
7 return newentry;
8 }
addbefore(e e,entry《e》 entry)方法是个私有方法,所以无法在外部程序中调用(当然,这是一般情况,你可以通过反射上面的还是能调用到的)。
addbefore(e e,entry《e》 entry)先通过entry的构造方法创建e的节点newentry(包含了将其下一个节点设置为entry,上一个节点设置为entry.previous的操作,相当于修改newentry的“指针”),之后修改插入位置后newentry的前一节点的next引用和后一节点的previous引用,使链表节点间的引用关系保持正确。之后修改和size大小和记录modcount,然后返回新插入的节点。
总结,addbefore(e e,entry《e》 entry)实现在entry之前插入由e构造的新节点。而add(e e)实现在header节点之前插入由e构造的新节点。
add(int index,e e)
1 public void add(int index, e element) {
2 addbefore(element, (index==size ? header : entry(index)));
3 }
也是调用了addbefore(e e,entry《e》 entry)方法,只是entry节点由index的值决定。
构造方法,addall(collection《? extends e》 c),add(e e),addbefor(e e,entry《e》 entry)方法可以构造链表并在指定位置插入节点,为了便于理解,下面给出插入节点的示意图。
addfirst(e e)
1 public void addfirst(e e) {
2 addbefore(e, header.next);
3 }
addlast(e e)
1 public void addlast(e e) {
2 addbefore(e, header);
3 }
看上面的示意图,结合addbefore(e e,entry《e》 entry)方法,很容易理解addfrist(e e)只需实现在header元素的下一个元素之前插入,即示意图中的一号之前。addlast(e e)只需在实现在header节点前(因为是循环链表,所以header的前一个节点就是链表的最后一个节点)插入节点(插入后在2号节点之后)。
clear()
1 public void clear() {
2 entry《e》 e = header.next;
3 // e可以理解为一个移动的“指针”,因为是循环链表,所以回到header的时候说明已经没有节点了
4 while (e != header) {
5 // 保留e的下一个节点的引用
6 entry《e》 next = e.next;
7 // 接触节点e对前后节点的引用
8 e.next = e.previous = null;
9 // 将节点e的内容置空
10 e.element = null;
11 // 将e移动到下一个节点
12 e = next;
13 }
14 // 将header构造成一个循环链表,同构造方法构造一个空的linkedlist
15 header.next = header.previous = header;
16 // 修改size
17 size = 0;
18 modcount++;
19 }
上面代码中的注释已经足以解释这段代码的逻辑,需要注意的是提到的“指针”仅仅是概念上的类比,java并不存在“指针”的概念,而只有引用,为了便于理解所以部分说明使用了“指针”。
contains(object o)
1 public boolean contains(object o) {
2 return indexof(o) != -1;
3 }
仅仅只是判断o在链表中的索引。先看indexof(object o)方法。
1 public int indexof(object o) {
2 int index = 0;
3 if (o==null) {
4 for (entry e = header.next; e != header; e = e.next) {
5 if (e.element==null)
6 return index;
7 index++;
8 }
9 } else {
10 for (entry e = header.next; e != header; e = e.next) {
11 if (o.equals(e.element))
12 return index;
13 index++;
14 }
15 }
16 return -1;
17 }
indexof(object o)判断o链表中是否存在节点的element和o相等,若相等则返回该节点在链表中的索引位置,若不存在则放回-1。
contains(object o)方法通过判断indexof(object o)方法返回的值是否是-1来判断链表中是否包含对象o。
element()
1 public e element() {
2 return getfirst();
3 }
getfirst()
1 public e getfirst() {
2 if (size==0)
3 throw new nosuchelementexception();
4 return header.next.element;
5 }
element()方法调用了getfirst()返回链表的第一个节点的元素。为什么要提供功能一样的两个方法,像是包装了一下名字?其实这只是为了在不同的上下文“语境”中能通过更贴切的方法名调用罢了。
get(int index)
1 public e get(int index) {
2 return entry(index).element;
3 }
get(int index)方法用于获得指定索引位置的节点的元素。它通过entry(int index)方法获取节点。entry(int index)方法遍历链表并获取节点,在上面有说明过,不再陈述。
set(int index,e element)
1 public e set(int index, e element) {
2 entry《e》 e = entry(index);
3 e oldval = e.element;
4 e.element = element;
5 return oldval;
6 }
先获取指定索引的节点,之后保留原来的元素,然后用element进行替换,之后返回原来的元素。
getlast()
1 public e getlast() {
2 if (size==0)
3 throw new nosuchelementexception();
4 return header.previous.element;
5 }
getlast()方法和getfirst()方法类似,只是获取的是header节点的前一个节点的元素。因为是循环链表,所以header节点的前一节点就是链表的最后一个节点。
lastindexof(object o)
1 public int lastindexof(object o) {
2 int index = size;
3 if (o==null) {
4 for (entry e = header.previous; e != header; e = e.previous) {
5 index--;
6 if (e.element==null)
7 return index;
8 }
9 } else {
10 for (entry e = header.previous; e != header; e = e.previous) {
11 index--;
12 if (o.equals(e.element))
13 return index;
14 }
15 }
16 return -1;
17 }
因为查找的是last index,即最后一次出现的位置,所以采用由后向前的遍历方式。因为采用了有后向前的遍历,所以index被赋值为size,并且循环体内执行时都进行减操作。分两种情况判断是否存在,分别是null和不为空。
offer(e e)
1 public boolean offer(e e) {
2 return add(e);
3 }
在链表尾部插入元素。
offerfirst(e e)
1 public boolean offerfirst(e e) {
2 addfirst(e);
3 return true;
4 }
在链表开头插入元素。
offerlast(e e)
1 public boolean offerlast(e e) {
2 addlast(e);
3 return true;
4 }
在链表末尾插入元素。
上面这三个方法都只是调用了相应的add方法,同样只是提供了不同的方法名在不同的语境下使用。
peek()
1 public e peek() {
2 if (size==0)
3 return null;
4 return getfirst();
5 }
peekfirst()
1 public e peekfirst() {
2 if (size==0)
3 return null;
4 return getfirst();
5 }
peeklast()
1 public e peeklast() {
2 if (size==0)
3 return null;
4 return getlast();
5 }
上面的三个方法也很简单,只是调用了对应的get方法。
poll()
1 public e poll() {
2 if (size==0)
3 return null;
4 return removefirst();
5 }
pollfirst()
1 public e pollfirst() {
2 if (size==0)
3 return null;
4 return removefirst();
5 }
polllast()
1 public e polllast() {
2 if (size==0)
3 return null;
4 return removelast();
5 }
poll相关的方法都是获取并移除某个元素。都是和remove操作相关。
pop()
1 public e pop() {
2 return removefirst();
3 }
push(e e)
1 public void push(e e) {
2 addfirst(e);
3 }
这两个方法对应栈的操作,即弹出一个元素和压入一个元素,仅仅是调用了removefirst()和addfirst()方法。
下面集中看remove相关操作的方法。
remove()
1 public e remove() {
2 return removefirst();
3 }
remove(int index)
1 public e remove(int index) {
2 return remove(entry(index));
3 }
remove(object o)
1 public boolean remove(object o) {
2 if (o==null) {
3 for (entry《e》 e = header.next; e != header; e = e.next) {
4 if (e.element==null) {
5 remove(e);
6 return true;
7 }
8 }
9 } else {
10 for (entry《e》 e = header.next; e != header; e = e.next) {
11 if (o.equals(e.element)) {
12 remove(e);
13 return true;
14 }
15 }
16 }
17 return false;
18 }
removefirst()
1 public e removefirst() {
2 return remove(header.next);
3 }
removelast()
1 public e removelast() {
2 return remove(header.previous);
3 }
removefirstoccurrence()
1 public boolean removefirstoccurrence(object o) {
2 return remove(o);
3 }
removelastoccurence()
1 public boolean removelastoccurrence(object o) {
2 if (o==null) {
3 for (entry《e》 e = header.previous; e != header; e = e.previous) {
4 if (e.element==null) {
5 remove(e);
6 return true;
7 }
8 }
9 } else {
10 for (entry《e》 e = header.previous; e != header; e = e.previous) {
11 if (o.equals(e.element)) {
12 remove(e);
13 return true;
14 }
15 }
16 }
17 return false;
18 }
几个remove方法最终都是调用了一个私有方法:remove(entry《e》 e),只是其他简单逻辑上的区别。下面分析remove(entry《e》 e)方法。
1 private e remove(entry《e》 e) {
2 if (e == header)
3 throw new nosuchelementexception();
4 // 保留将被移除的节点e的内容
5 e result = e.element;
6 // 将前一节点的next引用赋值为e的下一节点
7 e.previous.next = e.next;
8 // 将e的下一节点的previous赋值为e的上一节点
9 e.next.previous = e.previous;
10 // 上面两条语句的执行已经导致了无法在链表中访问到e节点,而下面解除了e节点对前后节点的引用
11 e.next = e.previous = null;
12 // 将被移除的节点的内容设为null
13 e.element = null;
14 // 修改size大小
15 size--;
16 modcount++;
17 // 返回移除节点e的内容
18 return result;
19 }
clone()
1 public object clone() {
2 linkedlist《e》 clone = null;
3 try {
4 clone = (linkedlist《e》) super.clone();
5 } catch (clonenotsupportedexception e) {
6 throw new internalerror();
7 }
8 clone.header = new entry《e》(null, null, null);
9 clone.header.next = clone.header.previous = clone.header;
10 clone.size = 0;
11 clone.modcount = 0;
12 for (entry《e》 e = header.next; e != header; e = e.next)
13 clone.add(e.element);
14 return clone;
15 }
调用父类的clone()方法初始化对象链表clone,将clone构造成一个空的双向循环链表,之后将header的下一个节点开始将逐个节点添加到clone中。最后返回克隆的clone对象。
toarray()
1 public object[] toarray() {
2 object[] result = new object[size];
3 int i = 0;
4 for (entry《e》 e = header.next; e != header; e = e.next)
5 result[i++] = e.element;
6 return result;
7 }
创建大小和linkedlist相等的数组result,遍历链表,将每个节点的元素element复制到数组中,返回数组。
toarray(t[] a)
1 public 《t》 t[] toarray(t[] a) {
2 if (a.length 《 size)
3 a = (t[])java.lang.reflect.array.newinstance(
4 a.getclass().getcomponenttype(), size);
5 int i = 0;
6 object[] result = a;
7 for (entry《e》 e = header.next; e != header; e = e.next)
8 result[i++] = e.element;
9 if (a.length 》 size)
10 a[size] = null;
11 return a;
12 }
先判断出入的数组a的大小是否足够,若大小不够则拓展。这里用到了发射的方法,重新实例化了一个大小为size的数组。之后将数组a赋值给数组result,遍历链表向result中添加的元素。最后判断数组a的长度是否大于size,若大于则将size位置的内容设置为null。返回a。
从代码中可以看出,数组a的length小于等于size时,a中所有元素被覆盖,被拓展来的空间存储的内容都是null;若数组a的length的length大于size,则0至size-1位置的内容被覆盖,size位置的元素被设置为null,size之后的元素不变。
为什么不直接对数组a进行操作,要将a赋值给result数组之后对result数组进行操作?
---------------------------------------------------------------------------------------------------------------------------------
linkedlist的iterator
除了entry,linkedlist还有一个内部类:listitr。
listitr实现了listiterator接口,可知它是一个迭代器,通过它可以遍历修改linkedlist。
在linkedlist中提供了获取listitr对象的方法:listiterator(int index)。
1 public listiterator《e》 listiterator(int index) {
2 return new listitr(index);
3 }
该方法只是简单的返回了一个listitr对象。
linkedlist中还有通过集成获得的listiterator()方法,该方法只是调用了listiterator(int index)并且传入0。
下面详细分析listitr。
1 private class listitr implements listiterator《e》 {
2 // 最近一次返回的节点,也是当前持有的节点
3 private entry《e》 lastreturned = header;
4 // 对下一个元素的引用
5 private entry《e》 next;
6 // 下一个节点的index
7 private int nextindex;
8 private int expectedmodcount = modcount;
9 // 构造方法,接收一个index参数,返回一个listitr对象
10 listitr(int index) {
11 // 如果index小于0或大于size,抛出indexoutofboundsexception异常
12 if (index 《 0 || index 》 size)
13 throw new indexoutofboundsexception(“index: ”+index+
14 “, size: ”+size);
15 // 判断遍历方向
16 if (index 《 (size 》》 1)) {
17 // next赋值为第一个节点
18 next = header.next;
19 // 获取指定位置的节点
20 for (nextindex=0; nextindex《index; nextindex++)
21 next = next.next;
22 } else {
23 // else中的处理和if块中的处理一致,只是遍历方向不同
24 next = header;
25 for (nextindex=size; nextindex》index; nextindex--)
26 next = next.previous;
27 }
28 }
29 // 根据nextindex是否等于size判断时候还有下一个节点(也可以理解为是否遍历完了linkedlist)
30 public boolean hasnext() {
31 return nextindex != size;
32 }
33 // 获取下一个元素
34 public e next() {
35 checkforcomodification();
36 // 如果nextindex==size,则已经遍历完链表,即没有下一个节点了(实际上是有的,因为是循环链表,任何一个节点都会有上一个和下一个节点,这里的没有下一个节点只是说所有节点都已经遍历完了)
37 if (nextindex == size)
38 throw new nosuchelementexception();
39 // 设置最近一次返回的节点为next节点
40 lastreturned = next;
41 // 将next“向后移动一位”
42 next = next.next;
43 // index计数加1
44 nextindex++;
45 // 返回lastreturned的元素
46 return lastreturned.element;
47 }
48
49 public boolean hasprevious() {
50 return nextindex != 0;
51 }
52 // 返回上一个节点,和next()方法相似
53 public e previous() {
54 if (nextindex == 0)
55 throw new nosuchelementexception();
56
57 lastreturned = next = next.previous;
58 nextindex--;
59 checkforcomodification();
60 return lastreturned.element;
61 }
62
63 public int nextindex() {
64 return nextindex;
65 }
66
67 public int previousindex() {
68 return nextindex-1;
69 }
70 // 移除当前iterator持有的节点
71 public void remove() {
72 checkforcomodification();
73 entry《e》 lastnext = lastreturned.next;
74 try {
75 linkedlist.this.remove(lastreturned);
76 } catch (nosuchelementexception e) {
77 throw new illegalstateexception();
78 }
79 if (next==lastreturned)
80 next = lastnext;
81 else
82 nextindex--;
83 lastreturned = header;
84 expectedmodcount++;
85 }
86 // 修改当前节点的内容
87 public void set(e e) {
88 if (lastreturned == header)
89 throw new illegalstateexception();
90 checkforcomodification();
91 lastreturned.element = e;
92 }
93 // 在当前持有节点后面插入新节点
94 public void add(e e) {
95 checkforcomodification();
96 // 将最近一次返回节点修改为header
97 lastreturned = header;
98 addbefore(e, next);
99 nextindex++;
100 expectedmodcount++;
101 }
102 // 判断expectedmodcount和modcount是否一致,以确保通过listitr的修改操作正确的反映在linkedlist中
103 final void checkforcomodification() {
104 if (modcount != expectedmodcount)
105 throw new concurrentmodificationexception();
106 }
107 }
下面是一个listitr的使用实例。
1 linkedlist《string》 list = new linkedlist《string》();
2 list.add(“first”);
3 list.add(“second”);
4 list.add(“thrid”);
5 system.out.println(list);
6 listiterator《string》 itr = list.listiterator();
7 while (itr.hasnext()) {
8 system.out.println(itr.next());
9 }
10 try {
11 system.out.println(itr.next());// throw exception
12 } catch (exception e) {
13 // todo: handle exception
14 }
15 itr = list.listiterator();
16 system.out.println(list);
17 system.out.println(itr.next());
18 itr.add(“new node1”);
19 system.out.println(list);
20 itr.add(“new node2”);
21 system.out.println(list);
22 system.out.println(itr.next());
23 itr.set(“modify node”);
24 system.out.println(list);
25 itr.remove();
26 system.out.println(list);
1 结果:
2 [first, second, thrid]
3 first
4 second
5 thrid
6 [first, second, thrid]
7 first
8 [first, new node1, second, thrid]
9 [first, new node1, new node2, second, thrid]
10 second
11 [first, new node1, new node2, modify node, thrid]
12 [first, new node1, new node2, thrid]
linkedlist还有一个提供iterator的方法:descendingiterator()。该方法返回一个descendingiterator对象。descendingiterator是linkedlist的一个内部类。
1 public iterator《e》 descendingiterator() {
2 return new descendingiterator();
3 }
下面分析详细分析descendingiterator类。
1 private class descendingiterator implements iterator {
2 // 获取listitr对象
3 final listitr itr = new listitr(size());
4 // hasnext其实是调用了itr的hasprevious方法
5 public boolean hasnext() {
6 return itr.hasprevious();
7 }
8 // next()其实是调用了itr的previous方法
9 public e next() {
10 return itr.previous();
11 }
12 public void remove() {
13 itr.remove();
14 }
15 }
从类名和上面的代码可以看出这是一个反向的iterator,代码很简单,都是调用的listitr类中的方法。

迈进汽车互联时代,华为车联网方案大放异彩
物联网企业争抢「两轮车换电」赛道
桥式整流电路为什么要用4个二极管
利用AMSVF进行混合信号SoC的全芯片验证
人工智能的“慧眼” 机器视觉技术
LinkedList的源码分析
FLIR对CVEDIAFLIR公司投资,将拓展AI技术
角度位移传感器的原理解析
精密配电列头柜监控模块的应用方案
微型热保护器在新能源汽车充电枪的应用-「安的电子」
STM32G0开发笔记:用PWM来实现LED呼吸灯效果
又一中国制造被德国人抢购一空
解析AI创业三大模式,下个产业浪潮的“独角兽”
当你沉浸在AR技术的体验时,是否想过会侵犯你的隐私
电动汽车轻量化或将是增加续航里程的最有效途径
做好通话录音设备,要考量这几个方面
荧光定量PCR仪的产品特点是怎样的
则成电子:​线路板和智能模组相关技术研发取得阶段性成果
浅谈人工智能新基建面临诸多挑战
晶体管是做什么的_晶体管的三个工作区是什么