一、JavaDoc 简介二、LinkedList 继承接口和实现类介绍三、LinkedList 基本方法介绍四、LinkedList 基本方法使用五、LinkedList 内部结构以及基本元素声明六、LinkedList 具体源码分析
java.util.LinkedList 继承了 AbstractSequentialList 并实现了List , Deque , Cloneable 接口,以及Serializable 接口
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable {}
类之间的继承体系如下:
下面就对继承树中的部分节点进行大致介绍:
AbstractSequentialList 介绍: 这个接口是List一系列子类接口的核心接口,以求最大限度的减少实现此接口的工作量,由顺序访问数据存储(例如链接链表)支持。对于随机访问的数据(像是数组),AbstractList 应该优先被使用这个接口可以说是与AbstractList类相反的,它实现了随机访问方法,提供了get(int index),set(int index,E element), add(int index,E element) and remove(int index)方法 对于程序员来说: 要实现一个列表,程序员只需要扩展这个类并且提供listIterator 和 size方法即可。 对于不可修改的列表来说, 程序员需要实现列表迭代器的 hasNext(), next(), hasPrevious(), previous 和 index 方法 AbstractList 介绍: 这个接口也是List继承类层次的核心接口,以求最大限度的减少实现此接口的工作量,由顺序访问 数据存储(例如链接链表)支持。对于顺序访问的数据(像是链表),AbstractSequentialList 应该优先被使用, 如果需要实现不可修改的list,程序员需要扩展这个类,list需要实现get(int) 方法和List.size()方法 如果需要实现可修改的list,程序员必须额外重写set(int,Object) set(int,E)方法(否则会抛出 UnsupportedOperationException的异常),如果list是可变大小的,程序员必须额外重写add(int,Object) , add(int, E) and remove(int) 方法 AbstractCollection 介绍: 这个接口是Collection接口的一个核心实现,尽量减少实现此接口所需的工作量 为了实现不可修改的collection,程序员应该继承这个类并提供呢iterator和size 方法 为了实现可修改的collection,程序团需要额外重写类的add方法,iterator方法返回的Iterator迭代器也必须实现remove方法
上面看完了LinkedList 的继承体系之后,来看看LinkedList的基本方法说明
上面图片的文字比较小,可能有些不清晰,下面我就来对上面图片做一个大致介绍:
学以致用,熟悉了上面基本方法之后,来简单做一个demo测试一下上面的方法:
/**
* 此方法描述
* LinedList 集合的基本使用
*/
public class LinkedListTest {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("111");
list.add("222");
list.add("333");
list.add(1,"123");
// 分别在头部和尾部添加元素
list.addFirst("top");
list.addLast("bottom");
System.out.println(list);
// 数组克隆
Object listClone = list.clone();
System.out.println(listClone);
// 创建一个首尾互换的迭代器
Iterator<String> it = list.descendingIterator();
while (it.hasNext()){
System.out.print(it.next() + " ");
}
System.out.println();
list.clear();
System.out.println("list.contains('111') ? " + list.contains("111"));
Collection<String> collec = Arrays.asList("123","213","321");
list.addAll(collec);
System.out.println(list);
System.out.println("list.element = " + list.element());
System.out.println("list.get(2) = " + list.get(2));
System.out.println("list.getFirst() = " + list.getFirst());
System.out.println("list.getLast() = " + list.getLast());
// 检索指定元素出现的位置
System.out.println("list.indexOf(213) = " + list.indexOf("213"));
list.add("123");
System.out.println("list.lastIndexOf(123) = " + list.lastIndexOf("123"));
// 在首部和尾部添加元素
list.offerFirst("first");
list.offerLast("999");
System.out.println("list = " + list);
list.offer("last");
// 只访问,不移除指定元素
System.out.println("list.peek() = " + list.peek());
System.out.println("list.peekFirst() = " + list.peekFirst());
System.out.println("list.peekLast() = " + list.peekLast());
// 访问并移除元素
System.out.println("list.poll() = " + list.poll());
System.out.println("list.pollFirst() = " + list.pollFirst());
System.out.println("list.pollLast() = " + list.pollLast());
System.out.println("list = " + list);
// 从首部弹出元素
list.pop();
// 压入元素
list.push("123");
System.out.println("list.size() = " + list.size());
System.out.println("list = " + list);
// remove操作
System.out.println(list.remove());
System.out.println(list.remove(1));
System.out.println(list.remove("999"));
System.out.println(list.removeFirst());
System.out.println("list = " + list);
list.addAll(collec);
list.addFirst("123");
list.addLast("123");
System.out.println("list = " + list);
list.removeFirstOccurrence("123");
list.removeLastOccurrence("123");
list.removeLast();
System.out.println("list = " + list);
list.addFirst("top");
list.addLast("bottom");
list.set(2,"321");
System.out.println("list = " + list);
System.out.println("--------------------------");
// 创建一个list的双向链表
ListIterator<String> listIterator = list.listIterator();
while(listIterator.hasNext()){
// 移到list的末端
System.out.println(listIterator.next());
}
System.out.println("--------------------------");
while (listIterator.hasPrevious()){
// 移到list的首端
System.out.println(listIterator.previous());
}
}
}输出:-------1------- [top, 111, 123, 222, 333, bottom]-------2-------[top, 111, 123, 222, 333, bottom]bottom 333 222 123 111 top list.contains('111') ? false[123, 213, 321]list.element = 123list.get(2) = 321list.getFirst() = 123list.getLast() = 321list.indexOf(213) = 1list.lastIndexOf(123) = 3-------4------- [first, 123, 213, 321, 123, 999]list.peek() = firstlist.peekFirst() = firstlist.peekLast() = lastlist.poll() = firstlist.pollFirst() = 123list.pollLast() = last-------5------- [213, 321, 123, 999]list.size() = 4-------6------- [123, 321, 123, 999]123123true321-------7------- []-------8------- [123, 123, 213, 321, 123]list = [123, 213]-------9------- [top, 123, 321, bottom]--------------------------top123321bottom--------------------------bottom321123top
每一个链表都是一个Node节点,由三个元素组成
private static class Node<E> { // Node节点的元素
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;
}
}
first 节点也是头节点, last节点也是尾节点
transient int size = 0; // 链表的容量
transient Node<E> first; // 指向第一个节点
transient Node<E> last; // 指向最后一个节点
/**
* 空构造函数
*/
public LinkedList() {}
/**
* 创建一个包含指定元素的构造函数
*/
public LinkedList(Collection<? extends E> c) { this(); addAll(c);
}
前言: 此源码是作者根据上面的代码示例一步一步跟进去的,如果有哪些疑问或者讲的不正确的地方,请与作者联系。
添加
添加的具体流程示意图:
包括方法有:
下面对这些方法逐个分析其源码:
add(E e) :
// 添加指定元素至list末尾
public boolean add(E e) {
linkLast(e);
return true;
}
// 真正添加节点的操作
void linkLast(E e) { final Node<E> l = last;
// 生成一个Node节点
final Node<E> newNode = new Node<>(l, e, null); last = newNode; // 如果l = null,代表的是第一个节点,所以这个节点即是头节点
// 又是尾节点 if (l == null)
first = newNode;
else
// 如果不是的话,那么就让该节点的next 指向新的节点
l.next = newNode;
size++;
modCount++;
}
add(int index,E e) :
/**
*在指定位置插入指定的元素
*/
public void add(int index, E element) {
// 下标检查
checkPositionIndex(index);
if (index == size)
// 如果需要插入的位置和链表的长度相同,就在链表的最后添加
linkLast(element);
else
// 否则就链接在此位置的前面
linkBefore(element, node(index));
}
// 越界检查
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
// 判断参数是否是有效位置(对于迭代或者添加操作来说)
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
// linkLast 上面已经介绍过
// 查找索引所在的节点
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;
}
}
// 在非空节点插入元素
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
// succ 即是插入位置的节点
// 查找该位置处的前面一个节点
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++;
}
addFirst(E e) :
// 在头节点插入元素
public void addFirst(E e) {
linkFirst(e);
}
private void linkFirst(E e) { // 先找到first 节点
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
// f 为null,也就代表着没有头节点
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
例如要添加top 元素至链表的首部,需要先找到first节点,如果first节点为null,也就说明没有头节点,如果不为null,则头节点的prev节点是新插入的节点。
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++;
}
方法逻辑与在头节点插入基本相同
addAll(Collections 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;
// 直接在末尾添加,所以index = size
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
// 遍历每个数组
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;
}
Collection<String> collec = Arrays.asList("123","213","321");
list.addAll(collec);
addAll(Collections c) : 这个方法的源码同上
offer也是对元素进行添加操作,源码和add方法相同
offerFirst(E e)和addFirst(E e) 源码相同
offerLast(E e)和addLast(E e) 源码相同)
push(E e) 和addFirst(E e) 源码相同
后记 : 笔者才疏学浅,如果有哪处错误产生误导,请及时与笔者联系更正,一起共建积极向上的it氛围
文章参考:
Java 集合系列05之 LinkedList详细介绍(源码解析)和使用示例
java双向链表示意图