JDK1.7版本
1、 LinkedList类定义,LinkedList底层的数据结构是基于双向链表的。
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
LinkedList 是一个继承于AbstractSequentialList的双向链表。它也可以被当作堆栈、队列或双端队列进行操作。
LinkedList 实现 List 接口,能对它进行队列操作。
LinkedList 实现 Deque 接口,即能将LinkedList当作双端队列使用。
LinkedList 实现了Cloneable接口,即覆盖了函数clone(),能克隆。
LinkedList 实现java.io.Serializable接口,这意味着LinkedList支持序列化,能通过序列化去传输。
LinkedList 是非同步的。
为什么要继承自AbstractSequentialList ?
AbstractSequentialList 实现了get(int index)、set(int index, E element)、add(int index, E element) 和 remove(int index)这些骨干性函数。降低了List接口的复杂度。这些接口都是随机访问List的,LinkedList是双向链表;既然它继承于AbstractSequentialList,就相当于已经实现了“get(int index)这些接口”。
此外,我们若需要通过AbstractSequentialList自己实现一个列表,只需要扩展此类,并提供 listIterator() 和 size() 方法的实现即可。若要实现不可修改的列表,则需要实现列表迭代器的 hasNext、next、hasPrevious、previous 和 index 方法即可。
LinkedList的类图关系:
2、私有属性
transient int size = 0;
transient Node<E> first;
transient Node<E> last;
size是双向链表中节点实例的个数。
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;
}
}
3、构造方法
public LinkedList() {
}
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
第一个是不带参数的;第二个构造方法接收一个Collection参数c,调用第一个构造方法构造一个空的链表,之后通过addAll将c中的元素全部添加到链表中。
4、添加节点
addAll,一些说明在代码中体现。下面同此。
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)//判断传入集合的大小,为0,则返回false
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) {//记录的后继节点若为空,则最后的节点设为pred;若有,则连接上上面的链表
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;//大小加入集合的大小
modCount++;//修改的次数
return true;
}
addFirst,addLast、add与addFirst雷同,不再说明
public void addFirst(E e) {
linkFirst(e);//调用私有方法linkFirst
}
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++;
}
5、删除节点
clean,清空链表
public void clear() {
for (Node<E> x = first; x != null; ) {//遍历链表,全部赋值为null
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
remove,removeFirst、removeLast
public E remove(int index) {
checkElementIndex(index);//检查下标的合法性
return unlink(node(index));
}
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;
}
6、修改节点
set
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);//获得修改下标的节点
E oldVal = x.item;//获取修改节点的原来的值返回
x.item = element;//修改此节点的值,前驱和后继保持不变
return oldVal;
}
7、查询节点
查询节点的长度size,就是返回私有属性size;get获取,getFirst和getLast实现原理相同。
public E get(int index) {
checkElementIndex(index);
return node(index).item;//直接返回此节点的值即可
}
8、contains,用来检测节点是否在此链表中,实现:
public boolean contains(Object o) {
return indexOf(o) != -1;//巧妙的用获取下标的值比较判断
}
public int indexOf(Object o) {//获取节点的下标
int index = 0;
if (o == null) {//此处为什么要分判断呢,因为Obeject类的equals方法不能被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;
}
9、转化为数组
toArray
public Object[] toArray() {
Object[] result = new Object[size];//实例化一个同等大小的Object数组,循环获取参数值赋给数组
int i = 0;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}
public <T> T[] toArray(T[] a) {
if (a.length < size)//小于链表的大小则通过反射新实例化一个同样的大小的数组
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;//同上一个方法
Object[] result = a;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}
10、遍历数据:Iterator()
LinkedList的Iterator
除了Node,LinkedList还有一个内部类:ListItr。
ListItr实现了ListIterator接口,可知它是一个迭代器,通过它可以遍历修改LinkedList。
在LinkedList中提供了获取ListItr对象的方法:listIterator(int index)。
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
该方法只是简单的返回了一个ListItr对象。
LinkedList中还有通过集成获得的listIterator()方法,该方法只是调用了listIterator(int index)并且传入0。
下面是LsitItr:
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned = null;
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++;
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
下面是一个ListItr的使用实例。
<span style="white-space:pre"> </span>LinkedList<String> list = new LinkedList<String>();
list.add("First");
list.add("Second");
list.add("Thrid");
System.out.println(list);
ListIterator<String> itr = list.listIterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
try {
System.out.println(itr.next());// throw Exception
} catch (Exception e) {
// TODO: handle exception
}
itr = list.listIterator();
System.out.println(list);
System.out.println(itr.next());
itr.add("new node1");
System.out.println(list);
itr.add("new node2");
System.out.println(list);
System.out.println(itr.next());
itr.set("modify node");
System.out.println(list);
itr.remove();
System.out.println(list);
结果:
[First, Second, Thrid]
First
Second
Thrid
[First, Second, Thrid]
First
[First, new node1, Second, Thrid]
[First, new node1, new node2, Second, Thrid]
Second
[First, new node1, new node2, modify node, Thrid]
[First, new node1, new node2, Thrid]
参考: