一、简介
上文我们探讨了线性表的顺序存储结构的实现 ArrayList,今天我们来讲链式存储结构的实现 LinkedList。LinkedList 是一个用链表实现的集合,元素有序且可以重复。今天我们来分析一下 LinkedList 的源码。
二、继承结构
和 ArrayList 集合一样,LinkedList 集合也实现了 Cloneable 接口和 Serializable 接口,分别用来支持克隆以及支持序列化。List 接口也不用多说,定义了一套 List 集合类型的方法规范。相对于 ArrayList 集合,LinkedList 集合多实现了一个 Deque 接口,这是一个双向队列接口,双向队列就是两端都可以进行增加和删除操作。
三、属性
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
// 链表元素(节点)的个数
transient int size = 0;
// 指向第一个节点的指针
transient Node<E> first;
// 指向最后一个节点的指针
transient Node<E> last;
}
注意这里出现了一个 Node 类,这是 LinkedList 类中的一个内部类,其中每一个元素就代表一个 Node 类对象,LinkedList 集合就是由许多个 Node 对象类似于手拉着手构成。
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;
}
}
四、构造方法
LinkedList 有两个构造方法,第一个是默认的无参构造方法,第二个是将已有元素的集合 Collection 的实例添加到 LinkedList 中,我们先看无参构造方法:
public LinkedList() {
}
注意:LinkedList 是没有初始化链表大小的构造函数,因为链表不像数组,一个定义好的数组是必须要有确定的大小,然后去分配内存空间,而链表不一样,它没有确定的大小,通过指针的移动来指向下一个内存地址的分配。
再来看一下以集合为参数的构造方法:
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
调用 addAll() 方法,将已有元素的集合 Collection 的实例添加到 LinkedList 中。
五、常用方法
0x01、新增操作
1.add(E e)
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++;
}
该方法在链表尾部添加一个新元素,成功返回 true。
2.add(int index, E element)
public void add(int index, E element) {
checkPositionIndex(index);
// 如果插入的位置正好是链表末尾
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
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++;
}
该方法在指定位置插入一个新的节点。
3.addFirst(E e)
public void addFirst(E e) {
linkFirst(e);
}
private void linkFirst(E e) {
// 记录下头节点
final Node<E> f = first;
// 创建新节点
final Node<E> newNode = new Node<>(null, e, f);
// 将新创建的节点作为头节点
first = newNode;
// 如果记录下的头节点为空
if (f == null)
// 将尾节点也指向新创建的节点
last = newNode;
else
// 将原先头节点的前驱设置为新创建的节点
f.prev = newNode;
size++;
modCount++;
}
该方法在链表的首部添加一个节点。
4.addLast(E e)
public void addLast(E e) {
linkLast(e);
}
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++;
}
该方法在链表的尾部添加一个节点。
5.addAll(Collection<? extends E> c)
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
public boolean addAll(int index, Collection<? extends E> c) {
// 判断下标是否合法
checkPositionIndex(index);
// 将要添加的集合转换为字符数组
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
// 创建两个节点,分别来存储要插入位置的节点和它的前驱节点
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
// 遍历 a 数组,将节点一个接一个的添加到之前记录前驱节点的后面
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;
}
0x02、删除操作
1.remove()
public E remove() {
return removeFirst();
}
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
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;
}
该方法删除第一个节点。
2.remove(int index)
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
// 通过遍历找到下标对应的节点
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;
}
}
// 将节点删除
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;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
该方法删除指定位置的元素。
3.remove(Object o)
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;
}
该方法删除指定元素。
4.removeLast()
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
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;
}
该方法删除最后一个元素。
0x03、查找操作
1.get(int index)
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
该方法得到指定位置的元素。
2.getFirst()
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
该方法得到首个元素。
3.getLast()
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
该方法得到最后一个元素。
0x04、具有队列性质的方法
因为 LinkedList 实现了 Deque 接口,所以 LinkedList 具有了双端队列的一些性质。
1.peek() 相关操作
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
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;
}
peek() 相关操作主要用来获取元素。
2.offer(E e) 相关操作
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;
}
offer(E e) 相关操作主要用来添加元素。
3.poll() 相关操作
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
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);
}
poll() 相关操作用来获取并删除元素。
4.push(E e)
public void push(E e) {
addFirst(e);
}
该方法用来向链表首部添加一个元素。
5.pop()
public E pop() {
return removeFirst();
}
该方法用来删除链表首部元素。
通过 push() 和 pop() 方法,LinkedList 还可以当作栈来使用。
六、遍历集合
0x01、普通 for 循环
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("A");
linkedList.add("B");
linkedList.add("C");
linkedList.add("D");
for(int i = 0 ; i < linkedList.size() ; i++){
System.out.print(linkedList.get(i)+" ");//A B C D
}
代码很简单,我们就利用 LinkedList 的 get(int index) 方法,遍历出所有的元素。
但是需要注意的是, get(int index) 方法每次都要遍历该索引之前的所有元素,这句话这么理解:
比如上面的一个 LinkedList 集合,我放入了 A,B,C,D 四个元素。总共需要四次遍历:
第一次遍历打印 A:只需遍历一次。
第二次遍历打印 B:需要先找到 A,然后再找到 B 打印。
第三次遍历打印 C:需要先找到 A,然后找到 B,最后找到 C 打印。
第四次遍历打印 D:需要先找到 A,然后找到 B,然后找到 C,最后找到 D。
这样如果集合元素很多,越查找到后面(当然此处的 get 方法进行了优化,查找前半部分从前面开始遍历,查找后半部分从后面开始遍历,但是需要的时间还是很多)花费的时间越多。那么如何改进呢?
0x02、迭代器
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("A");
linkedList.add("B");
linkedList.add("C");
linkedList.add("D");
Iterator<String> listIt = linkedList.listIterator();
while(listIt.hasNext()){
System.out.print(listIt.next() + " "); // A B C D
}
// 通过适配器模式实现的接口,作用是倒叙打印链表
Iterator<String> it = linkedList.descendingIterator();
while(it.hasNext()){
System.out.print(it.next()+" "); // D C B A
}
在 LinkedList 集合中也有一个内部类 ListItr,方法实现大体上也差不多,通过移动游标指向每一次要遍历的元素,不用在遍历某个元素之前都要从头开始。其方法实现也比较简单:
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned;
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++;
}
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (modCount == expectedModCount && nextIndex < size) {
action.accept(next.item);
lastReturned = next;
next = next.next;
nextIndex++;
}
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
这里需要重点注意的是 modCount 字段,前面我们在增加和删除元素的时候,都会进行自增操作 modCount,这是因为如果想一边迭代,一边用集合自带的方法进行删除或者新增操作,都会抛出异常(使用迭代器的增删方法不会抛异常)。
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
比如:
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("A");
linkedList.add("B");
linkedList.add("C");
linkedList.add("D");
Iterator<String> listIt = linkedList.listIterator();
while(listIt.hasNext()){
System.out.print(listIt.next() + " "); // A B C D
//linkedList.remove(); // 此处会抛出异常
listIt.remove(); // 这样可以进行删除操作
}
七、总结
-
LinkedList 实现了 Cloneable 接口和 Serializable 接口,分别用来支持克隆以及支持序列化。
-
LinkedList 集合实现了一个 Deque 接口,这是一个双向队列接口,双向队列就是两端都可以进行增加和删除操作,可以模拟队列操作。
-
通过 push() 和 pop() 方法,LinkedList 还可以当作栈来使用。
-
LinkedList 本质是链表,所以查询效率比较低,新增和删除效率比较高,在遍历时推荐使用迭代器访问。
参考
https://www.cnblogs.com/ysocean/p/8657850.html