LinkedList类实现了List接口以及Deque接口,并且是双向链表的实现版本;LinkedList类实现了所有可选的列表操作,并且允许添加包括null元素在内的所有的元素;
LinkedList类中的所有操作都可以认为是对双向链表使用的;
LinkedList类是非线程安全的。如果多个线程并发地访问一个LinkedList对象时,并且至少有一个线程从结构上修改了该链表,那么必须在外部对链表或者施加于链表上的操作进行同步。这里一般通过在包装了链表对象的对象上加锁实现同步,或者在创建链表的时候,通过Collections工具类的静态方法synchronizedList将链表进行包装,使其成为线程安全的链表;参考示例:
List list = Collections.synchronizedList(new LinkedList(...));
注意,上面说的的结构上的修改指的是:增加或删除一个或多个元素;仅仅设置一个元素的值并不是结构上的修改;
以下是LinkedList类的声明:
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable
可以看出,LinkedList类继承了AbstractSequentialList类并且是一个泛型类;同时,还实现了List、Deque、Cloneable和java.io.Serializable接口;List接口应该都熟悉,这里需要说一下的是Deque接口;
从JDK提供的该接口源码中可以得知,该接口是一个支持在两端进行插入和删除操作的线性集合。deque来自于”double ended queue”的简称,说明其是一个双端队列;大多数Deque接口的实现类对其可以容纳的元素的个数没有限制,但是这个接口也支持实现容量受限的双端队列;
此外,Deque接口扩展了Queue接口,Queue接口是队列接口;因此,当一个deque用作queue时,表现出先进先出的特点:队头删除,队尾插入;供其使用的方法全部来自于Queue接口(在Deque中也同样地提供了这些方法的等价方法);
Deque也可以用作一个后进先出的栈。当需要使用栈时,应该优先使用这一接口,而不是Stack类;当Deque被用作栈时,在deque的头部进行压入和弹出元素;在Deque接口中提供了与Stack类中的方法具有不同方法名但是功能相同的方法;
JDK开发人员明确指出:虽然没有严格限制null的插入,但是,强烈建议不要插入null元素!!!原因是,null元素作为许多方法的特殊返回值来表明deque是空的;
以下是LinkedList类的数据成员:
transient int size = 0;
//头指针
transient Node<E> first;
//尾指针
transient Node<E> last;
可以看出,上面三个数据成员都使用了transient关键字进行修饰,表明当LinkedList对象被持久化(串行化)时,这三个数据成员并不会被持久化;size用作记录当前链表对象已经容纳的元素个数;first是指向第一个节点的指针;last是指向最后一个节点的指针;
以下是LinkedList类提供的构造器:
//空链表
public LinkedList() {
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
第一个无参构造器用于创建一个空的链表;第二个构造器创建一个包含参数c集合中的所有元素的链表,该构造器内部先调用无参构造器创建一个空的链表,然后将集合c中的所有元素添加到已创建的空链表中;
以下是一些供公有方法调用的内部方法(非公有方法):
/**
* Links e as first element.
*/
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++;
}
/**
* 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;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
/**
* Inserts element e before non-null Node succ.
*/
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++;
}
/**
* 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 = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
/**
* 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 = prev;
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}
/**
* 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;
}
linkFirst(E e)方法将参数e插入链表头部,作为新链表的首元素;
linkLast(E e)方法将参数e插入链表的尾部,作为新链表的尾元素;
linkBefore(E e, Node succ)方法将参数e插入到非空节点succ之前;
unlinkFirst(Node f)方法删除链表中第一个非空节点(参数f);
unlinkLast(Node l)方法删除链表中最后一个非空节点(参数l);
unlink(Node x)方法删除链表中的指定非空节点x;
上面几个方法都是供LinkedList类中其他公有的增删操作调用的,这也很好地体现了代码的可重用性!
以下方法是供编程人员调用的增删链表中节点的公有方法,在这些方法的内部,调用了上面刚刚提过的内部非公有方法!
//返回第一个元素
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
//返回最后一个元素
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
//删除并返回第一个元素
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
//删除并返回最后一个元素
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
//首部插入元素
public void addFirst(E e) {
linkFirst(e);
}
//尾部插入元素
public void addLast(E e) {
linkLast(e);
}
//尾部插入元素
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* 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).
*/
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;
}
/**
* 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;
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;
}
/**
* 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++;
}
getFirst()方法返回链表中头结点中的数据部分;如果头结点为null,即链表为空,则抛出异常;
getLast()方法返回链表中尾节点中的数据部分;如果尾节点为null,即链表为空,则抛出异常;
removeFirst()方法删除链表中的头结点,如果头结点为null,即链表为空,则抛出异常;
removeLast()方法删除链表中的尾节点,如果尾节点为null,即链表为空,则抛出异常;
addFirst(E e)方法将指定参数e插入到链表的头部,作为头结点;
addLast(E e)方法将指定参数e插入到链表的尾部,作为尾节点;
add(E e)方法将参数e连接到当前链表的尾部;
remove(Object o)方法将指定元素从当前链表中删除;
addAll(Collection<? extends E> c)方法将给定参数c集合中的所有元素添加到当前链表尾部;
addAll(int index, Collection<? extends E> c)方法在当前链表索引位置为index处后添加给定参数c集合中的所有元素;
clear()方法清空链表中所有的节点;
以下方法都是基于位置的元素访问操作:
/**
* Returns {@code true} if this list contains the specified element.
* More formally, returns {@code true} if and only if this list contains
* at least one element {@code e} such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return {@code true} if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size() {
return size;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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(element);
else
linkBefore(element, node(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));
}
/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
/**
* 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;
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(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;
}
}
size()方法直接返回链表中元素个数;
contains(Object o)方法查询链表中是否包含指定元素o,其内部通过调用indexOf方法来判断是否包含于元素o相同的元素;
get(int index)方法查询位置索引为index的元素,并将其返回;通过观察该方法的内部实现,可知其先调用checkElementIndex(int index)方法进行判断位置的合法性,然后,才进行元素的返回;
set(int index, E element)方法将处于索引为index处的元素替换为指定参数element,同上,也调用了checkElementIndex(int index)方法进行判断位置的合法性;
add(int index, E element)方法在指定位置index处插入元素element,同上,调用了checkElementIndex方法;
remove(int index)方法删除指定位置index处的元素,同上,调用了checkElementIndex方法;
isElementIndex(int index)方法返回该索引是否为有效索引,即该索引处是否存在元素;
isPositionIndex(int index)方法判断指定参数index处是否可以插入元素;
outOfBoundsMsg方法构建一个指示错误信息的字符串;
checkElementIndex(int index)方法判断指定索引处是否存在元素;
checkPositionIndex(int index)方法判断指定索引处是否可以插入元素或进行迭代;
★★★node(int index)方法返回指定位置处的非空节点;这一方法需要特别说明一下,针对链表中定位一个元素,必须遍历整个链表这一缺点(相对于ArrayList类来说),源码中采用了一次折半查找来优化链表的定位操作,从而使得该查找的效率得到了一定的提高!!!
以下方法为查找方法以及队列或栈所使用的方法:
/**
* 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;
}
/**
* 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;
}
// Queue operations.
/**
* 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;
}
/**
* 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();
}
/**
* 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);
}
/**
* Retrieves and removes 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 remove() {
return removeFirst();
}
/**
* 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;
}
/**
* Retrieves, but does not remove, the first element of this list,
* or returns {@code null} if this list is empty.
*
* @return the first element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
/**
* Retrieves, but does not remove, the last element of this list,
* or returns {@code null} if this list is empty.
*
* @return the last element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}
/**
* Retrieves and removes the first element of this list,
* or returns {@code null} if this list is empty.
*
* @return the first element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* Retrieves and removes the last element of this list,
* or returns {@code null} if this list is empty.
*
* @return the last element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}
/**
* 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();
}
/**
* 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);
}
/**
* 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;
}
相对来说,LinkedList中的方法比ArrayList类中的方法要多,因为LinkedList类不仅可以作为线性表使用,还可以作为栈以及队列使用,因此,其方法相对来说就多出不少。
LinkedList类中的方法需要对链表的结构有一定的理解,在插入删除节点时,要注意前后节点的链接,不可以使其中断,或者缺少部分连接,要保证,新的链表能够正确无误地链接;
就个人理解,我觉得读完LinkedList类的源码之后,对该类的作用以及使用场景有了一定的理解,对其中代码结构的重用性进行学习,以及对其方法的编写风格有一定学习,就达到了初次阅读源码的目的!