写在前面:自己学习Java源码的一些笔记,JDK版本为1.8.0_131
属性
// 链表的长度
transient int size = 0;
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
// 链表的第一个元素
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
// 链表的最后一个元素
transient Node<E> last;
private static final long serialVersionUID = 876323262645176354L;
复制代码
其中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是一个双向链表。
构造器
1. LinkedList()
无参构造器。
/**
* Constructs an empty list.
*/
public LinkedList() {
}
复制代码
2. LinkedList(Collection<? extends E> c)
有参构造器,传入一个Collection。
/**
* 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);
}
复制代码
方法
1. node(int index)
获取指定索引处的结点。
/**
* Returns the (non-null) Node at the specified element 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;
}
}
复制代码
2. 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;
}
复制代码
其中linkLast(E e)源码为
/**
* Links e as last element.
*/
void linkLast(E e) {
// l 保存为链表的尾结点, final 修饰
final Node<E> l = last;
// 新建 Node,其前驱结点为尾结点,后继结点为null
final Node<E> newNode = new Node<>(l, e, null);
// 更新尾结点为新建结点
last = newNode;
// 如果 l 为 null,说明该链表只有新建结点一个元素,更新头结点为新建结点
// 否则,修改 l 的后继为新结点
if (l == null)
first = newNode;
else
l.next = newNode;
// 链表长度加一
size++;
modCount++;
}
复制代码
3. add(int index, E element)
在指定索引处添加元素。
/**
* 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);
// index == size 相当于在链表末尾添加元素,直接调用linkLast
if (index == size)
linkLast(element);
else
// 否则
linkBefore(element, node(index));
}
/**
* Inserts element e before non-null Node succ.
*/
//相当于在index与index - 1两个结点之间添加一个结点
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++;
}
// 检查索引处是否可以添加元素
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Tells if the argument is the index of a valid position for an
* iterator or an add operation.
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
复制代码
4. addAll(Collection<? extends E> c)
输入集合,将集合中的元素添加到链表的末尾。
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the specified
* collection's iterator. The behavior of this operation is undefined if
* the specified collection is modified while the operation is in
* progress. (Note that this will occur if the specified collection is
* this list, and it's nonempty.)
*
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(Collection<? extends E> c) {
// 在链表末尾添加结点
return addAll(size, c);
}
复制代码
实现将集合元素添加到指定索引处:
/**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
*
* @param index index at which to insert the first element
* from the specified collection
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws NullPointerException if the specified collection is null
*/
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,说明是在链表末尾添加结点,pred为尾结点
if (index == size) {
succ = null;
pred = last;
} else {
// 记录索引处的结点及其前驱结点
succ = node(index);
pred = succ.prev;
}
// 循环将每个结点加到上一个结点的后面
// 第一个结点会被添加到pred结点后面
for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)
// 新结点是链表的头结点,更新链表的first标记
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
// 在末尾添加元素,更新链表的last标记
if (succ == null) {
last = pred;
} else {
//是在链表中间插入结点
//此时添加的最后一个结点的后继应当指向原来在index位置的结点
pred.next = succ;
//更新原index处结点的前驱为加入的最后一个结点
succ.prev = pred;
}
// 更新链表实际长度
size += numNew;
modCount++;
return true;
}
复制代码
5. addFirst(E e)
该方法在链表头添加一个结点。
/**
* Inserts the specified element at the beginning of this list.
*
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}
复制代码
其中linkFirst(E e):
/**
* Links e as first element.
*/
private void linkFirst(E e) {
// 记录原结点,如果这个结点不为null,需要更新其前驱结点为新结点
final Node<E> f = first;
// 创建新结点,后继结点为原头节点
final Node<E> newNode = new Node<>(null, e, f);
// 更新first标记为新结点
first = newNode;
// f == null 说明链表中只有新结点一个元素
// 更新尾结点为新结点
// 否则更新原头结点的前驱为新结点
if (f == null)
last = newNode;
else
f.prev = newNode;
// 链表实际长度加一
size++;
modCount++;
}
复制代码
6. addLast(E e)
该方法在链表尾添加一个结点。
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #add}.
*
* @param e the element to add
*/
public void addLast(E e) {
// 见 add()
linkLast(e);
}
复制代码
7. getFirst()
获取头结点。
/**
* Returns the first element in this list.
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
复制代码
8. getLast()
获取尾结点。
/**
* Returns the last element in this list.
*
* @return the last element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
复制代码
9. get(int index)
获取指定索引处的结点。
/**
* 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;
}
复制代码
checkElementIndex(int index),索引需要在[0, siez)区间内,checkPositionIndex区间为[0, size]。
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
复制代码
10. 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);
E oldVal = x.item;
x.item = element;
return oldVal;
}
复制代码
11. removeFirst()
移除头节点
/**
* Removes and returns the first element from this list.
*
* @return the first element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
// 移除头结点
return unlinkFirst(f);
}
复制代码
unlinkFirst(Node<E> f)
/**
* Unlinks non-null first node 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标记
first = next;
// next == null 说明原链表只有一个元素,移除后已无元素
if (next == null)
last = null;
else
// 否则更新新的头结点的前驱为null
next.prev = null;
size--;
modCount++;
return element;
}
复制代码
12. removeLast()
移除链表中的最后一个结点
/**
* Removes and returns the last element from this list.
*
* @return the last element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
复制代码
unlinkLast(Node<E> l):
/**
* Unlinks non-null last node 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
last = prev;
if (prev == null)
first = null;
else
//新的尾结点的后继变为null
prev.next = null;
size--;
modCount++;
return element;
}
复制代码
13. remove(Object o)
删除链表中第一个的指定内容。
/**
* 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
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (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
*/
//通过从前往后遍历的方式,遍历到就调用unlink()
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;
}
复制代码
unlink(Node<E> x):
/**
* Unlinks non-null node x.
*/
// 如果结点 x 前后都有结点,将 x 的前驱结点指向 x 的后继结点
// 如果 x 是头结点更新 first 标记为 x 的后继
// 如果 x 是尾结点更新 last 标记为 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 {
// x 的前驱指向 x 的后继
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
// x 的后继的前驱指向 x 的前驱结点
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
复制代码
14. 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));
}
复制代码
15. removeFirstOccurrence(Object o)
与 remove(Object o) 相同。
/**
* Removes the first occurrence of the specified element in this
* list (when traversing the list from head to tail). If the list
* does not contain the element, it is unchanged.
*
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
* @since 1.6
*/
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
复制代码
16. removeLastOccurrence(Object o)
删除链表中最后一个item等于输入对象的结点。
/**
* Removes the last occurrence of the specified element in this
* list (when traversing the list from head to tail). If the list
* does not contain the element, it is unchanged.
*
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
* @since 1.6
*/
// 从后往前遍历
public boolean removeLastOccurrence(Object o) {
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
复制代码
17. indexOf(Object o)
返回在链表中第一次出现的索引。
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the first occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
复制代码
18. lastIndexOf(Object o)
返回在链表中最后一次出现的索引。
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the last occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
public int lastIndexOf(Object o) {
int index = size;
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (x.item == null)
return index;
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}
复制代码
19. peek()
返回链表头结点的内容,头结点为null,也会返回null。
/**
* Retrieves, but does not remove, the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
复制代码
20. element()
同样返回链表头结点的内容,但是如果头结点为null,会抛出异常。
/**
* Retrieves, but does not remove, the head (first element) of this list.
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
public E element() {
return getFirst();
}
/**
* Returns the first element in this list.
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
复制代码
21. poll()
返回链表头结点的内容,同时将从链表中删除头结点。
/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
复制代码
22. offer(E e) 和 offerFirst(E e) 和 offerLasst(E e)
offer和offerLast都是往链表末尾加结点,offerFirst是往链表开头加结点。
/**
* Adds the specified element as the tail (last element) of this list.
*
* @param e the element to add
* @return {@code true} (as specified by {@link Queue#offer})
* @since 1.5
*/
public boolean offer(E e) {
return add(e);
}
// Deque operations
/**
* Inserts the specified element at the front of this list.
*
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerFirst})
* @since 1.6
*/
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
/**
* Inserts the specified element at the end of this list.
*
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerLast})
* @since 1.6
*/
public boolean offerLast(E e) {
addLast(e);
return true;
}
复制代码
23. push(E e) 和 pop()
push在链表头加结点,pop删除头结点并返回。
/**
* Pushes an element onto the stack represented by this list. In other
* words, inserts the element at the front of this list.
*
* <p>This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @since 1.6
*/
public void push(E e) {
addFirst(e);
}
/**
* Pops an element from the stack represented by this list. In other
* words, removes and returns the first element of this list.
*
* <p>This method is equivalent to {@link #removeFirst()}.
*
* @return the element at the front of this list (which is the top
* of the stack represented by this list)
* @throws NoSuchElementException if this list is empty
* @since 1.6
*/
public E pop() {
return removeFirst();
}
复制代码
24. writeObject(java.io.ObjectOutputStream s) 和readObject(java.io.ObjectInputStream s)
重写了writeObject和readObject方法,序列化时会调用这两个方法。LinkedList中被tranisent修饰的属性有size, first 和 last,LinkedList序列化的时候只会保留结点的内容,其前驱和后继结点的指针不会被保留。反序列化的时候会重新构造链表。原因见以下链接。
ArrayList和LinkedList序列化与反序列化
/**
* Saves the state of this {@code LinkedList} instance to a stream
* (that is, serializes it).
*
* @serialData The size of the list (the number of elements it
* contains) is emitted (int), followed by all of its
* elements (each an Object) in the proper order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden serialization magic
s.defaultWriteObject();
// Write out size
s.writeInt(size);
// Write out all elements in the proper order.
for (Node<E> x = first; x != null; x = x.next)
s.writeObject(x.item);
}
/**
* Reconstitutes this {@code LinkedList} instance from a stream
* (that is, deserializes it).
*/
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic
s.defaultReadObject();
// Read in size
int size = s.readInt();
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
linkLast((E)s.readObject());
}
复制代码