LinkedList
简介
LinkedList 这个集合的底层是一个链表,特点是元素有序且可以重复。
类定义如下:
1public class LinkedList<E>
2 extends AbstractSequentialList<E>
3 implements List<E>, Deque<E>, Cloneable, java.io.Serializable {}
和 ArrayList 集合一样,LinkedList 集合也实现了 Cloneable 接口和 Serializable 接口,分别用来支持克隆以及支持序列化。List 接口也不用多说,定义了一套 List 集合类型的方法规范。
注意,相对于 ArrayList 集合,LinkedList 集合多实现了一个 Deque
接口,这是一个双向队列接口,双向队列就是两端都可以进行增加和删除操作。
字段属性
1// 元素(节点)的个数
2transient int size = 0;
3
4// 指向第一个节点的指针
5transient Node<E> first;
6
7// 指向最后一个节点的指针
8transient Node<E> last;
其中 Node 类是 LinkedList 类中的一个内部类,其中每一个元素代表一个 Node 类对象。
1private static class Node<E> {
2 E item;
3 Node<E> next;
4 Node<E> prev;
5
6 Node(Node<E> prev, E element, Node<E> next) {
7 this.item = element;
8 this.next = next;
9 this.prev = prev;
10 }
11}
在这个 Node 类中有 next 和 prev 指针,分别指向链表中上一个 node 和下一个 node
构造函数
1public LinkedList() {}
2
3public LinkedList(Collection<? extends E> c) {
4 this();
5 addAll(c);
6}
LinkedList 有两个构造函数,第一个是默认的空的构造函数,第二个是将已有元素的集合 Collection 的实例添加到 LinkedList 中,调用的是 addAll() 方法,这个方法下面我们会介绍。
注意:LinkedList 是没有初始化链表大小的构造函数,因为链表不像数组,一个定义好的数组是必须要有确定的大小,然后去分配内存空间,而链表不一样,它没有确定的大小,通过指针的移动来指向下一个内存地址的分配。
添加元素
- LinkedList 是没有虚节点的,第一个结点 prev 指向 null
addFirst(E e)
:将指定元素添加到链表头
addLast(E e) / add(E e)
:将指定元素添加到链表尾部
add(int index, E element)
:将指定的元素插入此链表中的指定位置
addAll(Collection<? extends E> c)
:按照指定集合的迭代器返回的顺序,将指定集合c中的所有元素追加到此链表的末尾
addAll(int index, Collection<? extends E> c)
:将集合 c 中所有元素插入到指定索引的位置。
- 其实 addAll(Collection<? extends E> c) == addAll(size, Collection<? extends E> c)
以上就是 LinkedList 集合中添加元素的各种方式,可以发现 LinkedList 每次添加元素只是改变元素的上一个指针引用和下一个指针引用,而且没有扩容。对比于 ArrayList ,是需要扩容的,而且在中间插入元素时,后面的所有元素都要移动一位,两者插入元素时的效率差异很大。
每次进行添加操作,都有modCount++ 的操作。
删除元素
删除元素和添加元素一样,也是通过更改指向上一个节点和指向下一个节点的引用即可,这里就不作图形展示了。
remove() / removeFirst()
:从列表中移除并返回第一个元素
removeLast()
:从列表中移除并返回最后一个元素
remove(int index)
:删除此链表中指定位置的元素,返回该元素
remove(Object o)
:如果存在,则从该链表中删除第一次出现的指定元素
- 此方法本质上和 remove(int index) 没多大区别,都是通过循环判断元素进行删除,需要注意的是,remove(Object o) 是只删除第一次出现的元素。
修改元素
set(int index, E element)
:用指定的元素替换此列表中指定位置的元素。
这里主要是通过 node(index) 方法获取指定索引位置的节点,然后修改此节点位置的元素即可。
查找元素
getFirst()
:返回此链表中的第一个元素
getLast()
:返回此链表中的最后一个元素
get(int index)
:返回指定索引处的元素
indexOf(Object o)
:返回此链表中指定元素第一次出现的索引,如果此链表不包含元素,则返回-1
遍历集合
先说区别:
-
普通for循环:每次遍历一个索引的元素之前,都要访问之前所有的索引。
-
每次访问一个元素后,都会用游标记录当前访问元素的位置,遍历一个元素,记录一个位置。
普通 for 循环
如下:
1LinkedList<String> linkedList = new LinkedList<>();
2linkedList.add("A");
3linkedList.add("B");
4linkedList.add("C");
5linkedList.add("D");
6for(int i = 0 ; i < linkedList.size() ; i++){
7 System.out.print(linkedList.get(i)+" ");
8}
需要注意的是, get(int index) 方法每次都要遍历该索引之前的所有元素,这句话这么理解:
比如上面的一个 LinkedList 集合,放入了 A、B、C、D 四个元素。总共需要四次遍历:
- 第一次遍历打印 A:只需遍历一次。
- 第二次遍历打印 B:需要先找到 A,然后再找到 B 打印。
- 第三次遍历打印 C:需要先找到 A,然后找到 B,最后找到 C 打印。
- 第四次遍历打印 D:需要先找到 A,然后找到 B,然后找到 C,最后找到 D。
也就是说每次调用 get(int index) 方法时,都是从最前面开始依次往后遍历。这样的话如果集合元素很多,越查找到后面(当然此处的get方法进行了优化,查找前半部分从前面开始遍历,查找后半部分从后面开始遍历,但是需要的时间还是很多)花费的时间越多。那么如何改进呢?
迭代器
如下:
1LinkedList<String> linkedList = new LinkedList<>();
2linkedList.add("A");
3linkedList.add("B");
4linkedList.add("C");
5linkedList.add("D");
6
7// 从前往后打印
8Iterator<String> listIt = linkedList.listIterator();
9while(listIt.hasNext()){
10 System.out.print(listIt.next()+" "); // A B C D
11}
12
13// 从后往前打印
14// 通过适配器模式实现的接口,作用是倒叙打印链表
15Iterator<String> it = linkedList.descendingIterator();
16while(it.hasNext()){
17 System.out.print(it.next()+" "); // D C B A
18}
在 LinkedList 集合中也有一个内部类 ListItr,方法实现大体上也差不多,通过移动游标指向每一次要遍历的元素,不用在遍历某个元素之前都要从头开始。其方法实现也比较简单:
1public ListIterator<E> listIterator(int index) {
2 checkPositionIndex(index);
3 return new ListItr(index);
4}
5
6private class ListItr implements ListIterator<E> {
7 private Node<E> lastReturned;
8 private Node<E> next;
9 private int nextIndex;
10 private int expectedModCount = modCount;
11
12 ListItr(int index) {
13 // assert isPositionIndex(index);
14 next = (index == size) ? null : node(index);
15 nextIndex = index;
16 }
17
18 public boolean hasNext() {
19 return nextIndex < size;
20 }
21
22 public E next() {
23 checkForComodification();
24 if (!hasNext())
25 throw new NoSuchElementException();
26
27 lastReturned = next;
28 next = next.next;
29 nextIndex++;
30 return lastReturned.item;
31 }
32
33 public boolean hasPrevious() {
34 return nextIndex > 0;
35 }
36
37 public E previous() {
38 checkForComodification();
39 if (!hasPrevious())
40 throw new NoSuchElementException();
41
42 lastReturned = next = (next == null) ? last : next.prev;
43 nextIndex--;
44 return lastReturned.item;
45 }
46
47 public int nextIndex() {
48 return nextIndex;
49 }
50
51 public int previousIndex() {
52 return nextIndex - 1;
53 }
54
55 public void remove() {
56 checkForComodification();
57 if (lastReturned == null)
58 throw new IllegalStateException();
59
60 Node<E> lastNext = lastReturned.next;
61 unlink(lastReturned);
62 if (next == lastReturned)
63 next = lastNext;
64 else
65 nextIndex--;
66 lastReturned = null;
67 expectedModCount++;
68 }
69
70 public void set(E e) {
71 if (lastReturned == null)
72 throw new IllegalStateException();
73 checkForComodification();
74 lastReturned.item = e;
75 }
76
77 public void add(E e) {
78 checkForComodification();
79 lastReturned = null;
80 if (next == null)
81 linkLast(e);
82 else
83 linkBefore(e, next);
84 nextIndex++;
85 expectedModCount++;
86 }
87
88 public void forEachRemaining(Consumer<? super E> action) {
89 Objects.requireNonNull(action);
90 while (modCount == expectedModCount && nextIndex < size) {
91 action.accept(next.item);
92 lastReturned = next;
93 next = next.next;
94 nextIndex++;
95 }
96 checkForComodification();
97 }
98
99 final void checkForComodification() {
100 if (modCount != expectedModCount)
101 throw new ConcurrentModificationException();
102 }
103}
这里需要重点注意的是 modCount 字段,前面在增加和删除元素的时候,都会进行自增操作 modCount,这是因为如果想一边迭代,一边用集合自带的方法进行删除或者新增操作,都会抛出异常。(使用迭代器的增删方法不会抛异常)
1final void checkForComodification() {
2 if (modCount != expectedModCount)
3 throw new ConcurrentModificationException();
4}
比如:
1LinkedList<String> linkedList = new LinkedList<>();
2linkedList.add("A");
3linkedList.add("B");
4linkedList.add("C");
5linkedList.add("D");
6
7Iterator<String> listIt = linkedList.listIterator();
8while(listIt.hasNext()){
9 System.out.print(listIt.next()+" "); // A B C D
10 // linkedList.remove(); // 此处会抛出异常
11 listIt.remove(); // 这样可以进行删除操作
12}
迭代器的另一种形式就是使用 foreach 循环,底层实现也是使用的迭代器:
1LinkedList<String> linkedList = new LinkedList<>();
2linkedList.add("A");
3linkedList.add("B");
4linkedList.add("C");
5linkedList.add("D");
6for(String str : linkedList){
7 System.out.print(str + "");
8}
迭代器和 for 循环性能差异测试
1LinkedList<Integer> linkedList = new LinkedList<>();
2for(int i = 0 ; i < 10000 ; i++){ // 向链表中添加一万个元素
3 linkedList.add(i);
4}
5
6long beginTimeFor = System.currentTimeMillis();
7for(int i = 0 ; i < 10000 ; i++){
8 System.out.print(linkedList.get(i));
9}
10long endTimeFor = System.currentTimeMillis();
11System.out.println("使用普通for循环遍历10000个元素需要的时间:"+ (endTimeFor - beginTimeFor));
12
13long beginTimeIte = System.currentTimeMillis();
14Iterator<Integer> it = linkedList.listIterator();
15while(it.hasNext()){
16 System.out.print(it.next()+" ");
17}
18long endTimeIte = System.currentTimeMillis();
19System.out.println("使用迭代器遍历10000个元素需要的时间:"+ (endTimeIte - beginTimeIte));
打印结果:
1使用普通for循环遍历10000个元素需要的时间:100
2使用迭代器遍历10000个元素需要的时间:24
可以看出当打印10000个元素时,两者的时间大约相差3倍,当元素个数更多时,性能差距将会更大。