继承体系图
LinkedList内部是由双链表组成的,里面存放着一个个Node,每个Node又包含三个元素(prev,item,next):
- prev:指向前一个Node
- item:存放存入的数据
- next:指向下一个Node
节点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;
}
}
链表的第一个Node的prev为null,最后个Node的next为null。
画了一张图,更好的展示LinkedList的结构:
重要属性
相比于Arraylist,LinkedList的属性就少得多,就只有三个,size存这当前元素的个数,first指向链表的第一个节点,last指向链表的最后一个节点。
transient int size = 0;
/**
* Pointer to first node.
*/
transient Node<E> first;
/**
* Pointer to last node.
*/
transient Node<E> last;
构造函数
无参构造方法
/**
* Constructs an empty list.
*/
public LinkedList() {
}
无参构造只是构造了一个空链表,并未做任何操作,此时,size=0, first=null, last=null。
有参构造方法
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
该构造方法的参数可以是ArrayList也可以是LinkedList,里面的操作就相当于把集合里的元素复制到新集合里面。
get方法
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
checkElementIndex(index); //判断是否越界
return node(index).item; //查找节点,然后返回节点的数据项item
}
//node方法,进行遍历链表,查找index位置的节点并返回
/**
* Returns the (non-null) Node at the specified element index.
*/
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {//如果查找的元素在LinkedList的前半部分,就从第一个元素开始往后找
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {//如果查找的元素在LinkedList的后半部分,就从最后一个元素开始往前找
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
add方法
add(E e)方法
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
linkLast(e); //链接到最后一个元素
return true;
}
/**
* Links e as last element.
*/
void linkLast(E e) {
final Node<E> l = last; //保存原先链表的最后一个节点
final Node<E> newNode = new Node<>(l, e, null); //创建一个新的节点
last = newNode; //将last指向新添加的newNode
if (l == null) //如果原先链表的最后一个节点为null,则说明是第一次添加节点,将first也指向这个新添加的Node
first = newNode;
else
l.next = newNode; //如果不是第一次添加节点,则将原先链表的最后一个节点的next指向新添加的Node
size++;
modCount++;
}
图示:
第一次添加新节点:
不是第一次添加新节点:
add(int index, E element)方法
插入元素时,先判断插入的位置是不是尾部,如果不是尾部的话,先调用和get()那个一样的方法,来查找要插入位置的当前元素,然后进行插入操作。
/**
* Inserts the specified element at the specified position in this list.
* Shifts the element currently at that position (if any) and any
* subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)//如果插入的位置是末尾,则直接调用linkLast方法
linkLast(element);
else
linkBefore(element, node(index)); //如果插入的位置不是末尾,先调用node(index)方法查找要插入位置处的节点,然后调用linkBefore方法进行插入
}
/**
* Inserts element e before non-null Node succ.
*/
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev; //保存被插入节点的prev所指向的Node
final Node<E> newNode = new Node<>(pred, e, succ);//构建一个新的Node
succ.prev = newNode; //被插入节点的prev指向新的Node
if (pred == null)//判断被插入节点是不是第一个节点
first = newNode; //如果是,就把first指向新的Node
else
pred.next = newNode; //如果不是,就把被插入节点的prev所指向的Node的next指向新的Node
size++;
modCount++;
}
图示:
新添加的节点的位置是第一个:
新添加的节点的位置不是第一个:
set方法
set(int index, E element)
/**
* Replaces the element at the specified position in this list with the
* specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index); //先调用node(index)方法查找要修改位置处的节点
E oldVal = x.item; //保存Node的旧的item
x.item = element; //将被修改的Node的item值设置为新的值
return oldVal; //返回旧的item
}
先调用node方法查找要修改位置处的节点,然后修改该节点的item值。
remove方法
remove(int index)
/**
* Removes the element at the specified position in this list. Shifts any
* subsequent elements to the left (subtracts one from their indices).
* Returns the element that was removed from the list.
*
* @param index the index of the element to be removed
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
/**
* Unlinks non-null node 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;
}
图示;
删除的是链表里的第一个元素:
删除的是链表里的中间元素:
删除的是链表里的最后一个元素:
remove(Object o)
这个删除就比较慢了,从头开始一一对比,时间复杂度为O(n),这个删除也是只删除最早添加的那个数据。
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If this list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* {@code i} such that
* {@code Objects.equals(o, get(i))}
* (if such an element exists). Returns {@code true} if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return {@code true} if this list contained the specified element
*/
public boolean remove(Object o) {
if (o == null) { //由于LinkedList是可以添加null数据的,所以从头开始遍历,有节点的item为null的就调用unlink解除该Node的相关链接
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else { //如果删除的不是null,还是从头开始遍历,调用equals方法进行比较,如果某个节点的item与传入的数据相同,就调用unlink解除该Node的相关链接
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
clear方法
/**
* Removes all of the elements from this list.
* The list will be empty after this call returns.
*/
public void clear() {
// Clearing all of the links between nodes is "unnecessary", but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
clear方法很简单,遍历整个链表,把链表的所有Node的三个变量都置为null,最后把LinkedList的first和last都置为null,size置为0;
总结
如果要删除元素时,最好选择传入索引进行删除,他比直接传入要删除的对象的方法要快很多
参考:
【源码解析】面试必问的LinkedList,看这篇文章就够了
面试必备:LinkedList源码解析(JDK8)
面试官系统精讲Java源码及大厂真题 - 06 LinkedList 源码解析
一篇文章搞定ArrayList和LinkedList所有面试问题