LinkedList也和ArrayList一样实现了List接口
但是它执行插入和删除操作时比ArrayList更加高效
因为它是基于链表的
基于链表也决定了它在随机访问方面要比ArrayList逊色一点
除此之外LinkedList还提供了一些可以使其作为栈队列双端队列的方法这些方法中有些彼此之间只是名称的区别以使得这些名字在特定的上下文中显得更加的合适
先看LinkedList类的定义
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E> Deque<E> Cloneable javaioSerializable
LinkedList继承自AbstractSequenceList实现了List及Deque接口其实AbstractSequenceList已经实现了List接口这里标注出List只是更加清晰而已AbstractSequenceList提供了List接口骨干性的实现以减少实现List接口的复杂度Deque接口定义了双端队列的操作
LinkedList中之定义了两个属性
private transient Entry<E> header = new Entry<E>(null null null);
private transient int size = ;
size肯定就是LinkedList对象里面存储的元素个数了LinkedList既然是基于链表实现的那么这个header肯定就是链表的头结点了Entry就是节点对象了一下是Entry类的代码
private static class Entry<E> {
E element;
Entry<E> next;
Entry<E> previous;
Entry(E element Entry<E> next Entry<E> previous) {
thiselement = element;
thisnext = next;
thisprevious = previous;
}
}
只定义了存储的元素前一个元素后一个元素这就是双向链表的节点的定义每个节点只知道自己的前一个节点和后一个节点
来看LinkedList的构造方法
public LinkedList() {
headernext = headerprevious = header;
}
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
LinkedList提供了两个构造方法第一个构造方法不接受参数只是将header节点的前一节点和后一节点都设置为自身(注意这个是一个双向循环链表如果不是循环链表空链表的情况应该是header节点的前一节点和后一节点均为null)这样整个链表其实就只有header一个节点用于表示一个空的链表第二个构造方法接收一个Collection参数c调用第一个构造方法构造一个空的链表之后通过addAll将c中的元素全部添加到链表中来看addAll的内容
public boolean addAll(Collection<? extends E> c) {
return addAll(size c);
}
// index参数指定collection中插入的第一个元素的位置
public boolean addAll(int index Collection<? extends E> c) {
// 插入位置超过了链表的长度或小于报IndexOutOfBoundsException异常
if (index < || index > size)
throw new IndexOutOfBoundsException(Index: +index+
Size: +size);
Object[] a = ctoArray();
int numNew = alength;
// 若需要插入的节点个数为则返回false表示没有插入元素
if (numNew==)
return false;
modCount++;
// 保存index处的节点插入位置如果是size则在头结点前面插入否则获取index处的节点
Entry<E> successor = (index==size ? header : entry(index));
// 获取前一个节点插入时需要修改这个节点的next引用
Entry<E> predecessor = successorprevious;
// 按顺序将a数组中的第一个元素插入到index处将之后的元素插在这个元素后面
for (int i=; i<numNew; i++) {
// 结合Entry的构造方法这条语句是插入操作相当于C语言中链表中插入节点并修改指针
Entry<E> e = new Entry<E>((E)a[i] successor predecessor);
// 插入节点后将前一节点的next指向当前节点相当于修改前一节点的next指针
predecessornext = e;
// 相当于C语言中成功插入元素后将指针向后移动一个位置以实现循环的功能
predecessor = e;
}
// 插入元素前index处的元素链接到插入的Collection的最后一个节点
successorprevious = predecessor;
// 修改size
size += numNew;
return true;
}
构造方法中的调用了addAll(Collection<? extends E> c)方法而在addAll(Collection<? extends E> c)方法中仅仅是将size当做index参数调用了addAll(int indexCollection<? extends E> c)方法
private Entry<E> entry(int index) {
if (index < || index >= size)
throw new IndexOutOfBoundsException(Index: +index+
Size: +size);
Entry<E> e = header;
// 根据这个判断决定从哪个方向遍历这个链表
if (index < (size >> )) {
for (int i = ; i <= index; i++)
e = enext;
} else {
// 可以通过header节点向前遍历说明这个一个循环双向链表header的previous指向链表的最后一个节点这也验证了构造方法中对于header节点的前后节点均指向自己的解释
for (int i = size; i > index; i)
e = eprevious;
}
return e;
}
结合上面代码中的注释及双向循环链表的知识应该很容易理解LinkedList构造方法所涉及的内容下面开始分析LinkedList的其他方法
add(E e)
public boolean add(E e) {
addBefore(e header);
return true;
}
从上面的代码可以看出add(E e)方法只是调用了addBefore(E eEntry<E> entry)方法并且返回true
addBefore(E eEntry<E> entry)
private Entry<E> addBefore(E e Entry<E> entry) {
Entry<E> newEntry = new Entry<E>(e entry entryprevious);
newEntrypreviousnext = newEntry;
newEntrynextprevious = newEntry;
size++;
modCount++;
return newEntry;
}
addBefore(E eEntry<E> entry)方法是个私有方法所以无法在外部程序中调用(当然这是一般情况你可以通过反射上面的还是能调用到的)
addBefore(E eEntry<E> entry)先通过Entry的构造方法创建e的节点newEntry(包含了将其下一个节点设置为entry上一个节点设置为entryprevious的操作相当于修改newEntry的指针)之后修改插入位置后newEntry的前一节点的next引用和后一节点的previous引用使链表节点间的引用关系保持正确之后修改和size大小和记录modCount然后返回新插入的节点
总结addBefore(E eEntry<E> entry)实现在entry之前插入由e构造的新节点而add(E e)实现在header节点之前插入由e构造的新节点
add(int indexE e)
public void add(int index E element) {
addBefore(element (index==size ? header : entry(index)));
}
也是调用了addBefore(E eEntry<E> entry)方法只是entry节点由index的值决定
构造方法addAll(Collection<? extends E> c)add(E e)addBefor(E eEntry<E> entry)方法可以构造链表并在指定位置插入节点为了便于理解下面给出插入节点的示意图
addFirst(E e)
public void addFirst(E e) {
addBefore(e headernext);
}
addLast(E e)
public void addLast(E e) {
addBefore(e header);
}
看上面的示意图结合addBefore(E eEntry<E> entry)方法很容易理解addFrist(E e)只需实现在header元素的下一个元素之前插入即示意图中的一号之前addLast(E e)只需在实现在header节点前(因为是循环链表所以header的前一个节点就是链表的最后一个节点)插入节点(插入后在号节点之后)
clear()
public void clear() {
Entry<E> e = headernext;
// e可以理解为一个移动的指针因为是循环链表所以回到header的时候说明已经没有节点了
while (e != header) {
// 保留e的下一个节点的引用
Entry<E> next = enext;
// 接触节点e对前后节点的引用
enext = eprevious = null;
// 将节点e的内容置空
eelement = null;
// 将e移动到下一个节点
e = next;
}
// 将header构造成一个循环链表同构造方法构造一个空的LinkedList
headernext = headerprevious = header;
// 修改size
size = ;
modCount++;
}
上面代码中的注释已经足以解释这段代码的逻辑需要注意的是提到的指针仅仅是概念上的类比Java并不存在指针的概念而只有引用为了便于理解所以部分说明使用了指针
contains(Object o)
public boolean contains(Object o) {
return indexOf(o) != ;
}
仅仅只是判断o在链表中的索引先看indexOf(Object o)方法
public int indexOf(Object o) {
int index = ;
if (o==null) {
for (Entry e = headernext; e != header; e = enext) {
if (eelement==null)
return index;
index++;
}
} else {
for (Entry e = headernext; e != header; e = enext) {
if (oequals(eelement))
return index;
index++;
}
}
return ;
}
indexOf(Object o)判断o链表中是否存在节点的element和o相等若相等则返回该节点在链表中的索引位置若不存在则放回
contains(Object o)方法通过判断indexOf(Object o)方法返回的值是否是来判断链表中是否包含对象o
element()
public E element() {
return getFirst();
}
getFirst()
public E getFirst() {
if (size==)
throw new NoSuchElementException();
return headernextelement;
}
element()方法调用了getFirst()返回链表的第一个节点的元素为什么要提供功能一样的两个方法像是包装了一下名字?其实这只是为了在不同的上下文语境中能通过更贴切的方法名调用罢了
get(int index)
public E get(int index) {
return entry(index)element;
}
get(int index)方法用于获得指定索引位置的节点的元素它通过entry(int index)方法获取节点entry(int index)方法遍历链表并获取节点在上面有说明过不再陈述
set(int indexE element)
public E set(int index E element) {
Entry<E> e = entry(index);
E oldVal = eelement;
eelement = element;
return oldVal;
}
先获取指定索引的节点之后保留原来的元素然后用element进行替换之后返回原来的元素
getLast()
public E getLast() {
if (size==)
throw new NoSuchElementException();
return headerpreviouselement;
}
getLast()方法和getFirst()方法类似只是获取的是header节点的前一个节点的元素因为是循环链表所以header节点的前一节点就是链表的最后一个节点
lastIndexOf(Object o)
public int lastIndexOf(Object o) {
int index = size;
if (o==null) {
for (Entry e = headerprevious; e != header; e = eprevious) {
index;
if (eelement==null)
return index;
}
} else {
for (Entry e = headerprevious; e != header; e = eprevious) {
index;
if (oequals(eelement))
return index;
}
}
return ;
}
因为查找的是last index即最后一次出现的位置所以采用由后向前的遍历方式因为采用了有后向前的遍历所以index被赋值为size并且循环体内执行时都进行减操作分两种情况判断是否存在分别是null和不为空
offer(E e)
public boolean offer(E e) {
return add(e);
}
在链表尾部插入元素
offerFirst(E e)
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
在链表开头插入元素
offerLast(E e)
public boolean offerLast(E e) {
addLast(e);
return true;
}
在链表末尾插入元素
上面这三个方法都只是调用了相应的add方法同样只是提供了不同的方法名在不同的语境下使用
peek()
public E peek() {
if (size==)
return null;
return getFirst();
}
peekFirst()
public E peekFirst() {
if (size==)
return null;
return getFirst();
}
peekLast()
public E peekLast() {
if (size==)
return null;
return getLast();
}
上面的三个方法也很简单只是调用了对应的get方法
poll()
public E poll() {
if (size==)
return null;
return removeFirst();
}
pollFirst()
public E pollFirst() {
if (size==)
return null;
return removeFirst();
}
pollLast()
public E pollLast() {
if (size==)
return null;
return removeLast();
}
poll相关的方法都是获取并移除某个元素都是和remove操作相关
pop()
public E pop() {
return removeFirst();
}
push(E e)
public void push(E e) {
addFirst(e);
}
这两个方法对应栈的操作即弹出一个元素和压入一个元素仅仅是调用了removeFirst()和addFirst()方法
下面集中看remove相关操作的方法
remove()
public E remove() {
return removeFirst();
}
remove(int index)
public E remove(int index) {
return remove(entry(index));
}
remove(Object o)
public boolean remove(Object o) {
if (o==null) {
for (Entry<E> e = headernext; e != header; e = enext) {
if (eelement==null) {
remove(e);
return true;
}
}
} else {
for (Entry<E> e = headernext; e != header; e = enext) {
if (oequals(eelement)) {
remove(e);
return true;
}
}
}
return false;
}
removeFirst()
public E removeFirst() {
return remove(headernext);
}
removeLast()
public E removeLast() {
return remove(headerprevious);
}
removeFirstOccurrence()
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
removeLastOccurence()
public boolean removeLastOccurrence(Object o) {
if (o==null) {
for (Entry<E> e = headerprevious; e != header; e = eprevious) {
if (eelement==null) {
remove(e);
return true;
}
}
} else {
for (Entry<E> e = headerprevious; e != header; e = eprevious) {
if (oequals(eelement)) {
remove(e);
return true;
}
}
}
return false;
}
几个remove方法最终都是调用了一个私有方法remove(Entry<E> e)只是其他简单逻辑上的区别下面分析remove(Entry<E> e)方法
private E remove(Entry<E> e) {
if (e == header)
throw new NoSuchElementException();
// 保留将被移除的节点e的内容
E result = eelement;
// 将前一节点的next引用赋值为e的下一节点
epreviousnext = enext;
// 将e的下一节点的previous赋值为e的上一节点
enextprevious = eprevious;
// 上面两条语句的执行已经导致了无法在链表中访问到e节点而下面解除了e节点对前后节点的引用
enext = eprevious = null;
// 将被移除的节点的内容设为null
eelement = null;
// 修改size大小
size;
modCount++;
// 返回移除节点e的内容
return result;
}
clone()
public Object clone() {
LinkedList<E> clone = null;
try {
clone = (LinkedList<E>) superclone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
cloneheader = new Entry<E>(null null null);
cloneheadernext = cloneheaderprevious = cloneheader;
clonesize = ;
clonemodCount = ;
for (Entry<E> e = headernext; e != header; e = enext)
cloneadd(eelement);
return clone;
}
调用父类的clone()方法初始化对象链表clone将clone构造成一个空的双向循环链表之后将header的下一个节点开始将逐个节点添加到clone中最后返回克隆的clone对象
toArray()
public Object[] toArray() {
Object[] result = new Object[size];
int i = ;
for (Entry<E> e = headernext; e != header; e = enext)
result[i++] = eelement;
return result;
}
创建大小和LinkedList相等的数组result遍历链表将每个节点的元素element复制到数组中返回数组
toArray(T[] a)
public <T> T[] toArray(T[] a) {
if (alength < size)
a = (T[])javalangreflectArraynewInstance(
agetClass()getComponentType() size);
int i = ;
Object[] result = a;
for (Entry<E> e = headernext; e != header; e = enext)
result[i++] = eelement;
if (alength > size)
a[size] = null;
return a;
}
先判断出入的数组a的大小是否足够若大小不够则拓展这里用到了发射的方法重新实例化了一个大小为size的数组之后将数组a赋值给数组result遍历链表向result中添加的元素最后判断数组a的长度是否大于size若大于则将size位置的内容设置为null返回a
从代码中可以看出数组a的length小于等于size时a中所有元素被覆盖被拓展来的空间存储的内容都是null若数组a的length的length大于size则至size位置的内容被覆盖size位置的元素被设置为nullsize之后的元素不变
为什么不直接对数组a进行操作要将a赋值给result数组之后对result数组进行操作?
LinkedList的Iterator
除了EntryLinkedList还有一个内部类ListItr
ListItr实现了ListIterator接口可知它是一个迭代器通过它可以遍历修改LinkedList
在LinkedList中提供了获取ListItr对象的方法listIterator(int index)
public ListIterator<E> listIterator(int index) {
return new ListItr(index);
}
该方法只是简单的返回了一个ListItr对象
LinkedList中还有通过集成获得的listIterator()方法该方法只是调用了listIterator(int index)并且传入
下面详细分析ListItr
private class ListItr implements ListIterator<E> {
// 最近一次返回的节点也是当前持有的节点
private Entry<E> lastReturned = header;
// 对下一个元素的引用
private Entry<E> next;
// 下一个节点的index
private int nextIndex;
private int expectedModCount = modCount;
// 构造方法接收一个index参数返回一个ListItr对象
ListItr(int index) {
// 如果index小于或大于size抛出IndexOutOfBoundsException异常
if (index < || index > size)
throw new IndexOutOfBoundsException(Index: +index+
Size: +size);
// 判断遍历方向
if (index < (size >> )) {
// next赋值为第一个节点
next = headernext;
// 获取指定位置的节点
for (nextIndex=; nextIndex<index; nextIndex++)
next = nextnext;
} else {
// else中的处理和if块中的处理一致只是遍历方向不同
next = header;
for (nextIndex=size; nextIndex>index; nextIndex)
next = nextprevious;
}
}
// 根据nextIndex是否等于size判断时候还有下一个节点(也可以理解为是否遍历完了LinkedList)
public boolean hasNext() {
return nextIndex != size;
}
// 获取下一个元素
public E next() {
checkForComodification();
// 如果nextIndex==size则已经遍历完链表即没有下一个节点了(实际上是有的因为是循环链表任何一个节点都会有上一个和下一个节点这里的没有下一个节点只是说所有节点都已经遍历完了)
if (nextIndex == size)
throw new NoSuchElementException();
// 设置最近一次返回的节点为next节点
lastReturned = next;
// 将next向后移动一位
next = nextnext;
// index计数加
nextIndex++;
// 返回lastReturned的元素
return lastReturnedelement;
}
public boolean hasPrevious() {
return nextIndex != ;
}
// 返回上一个节点和next()方法相似
public E previous() {
if (nextIndex == )
throw new NoSuchElementException();
lastReturned = next = nextprevious;
nextIndex;
checkForComodification();
return lastReturnedelement;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex;
}
// 移除当前Iterator持有的节点
public void remove() {
checkForComodification();
Entry<E> lastNext = lastReturnednext;
try {
LinkedListthisremove(lastReturned);
} catch (NoSuchElementException e) {
throw new IllegalStateException();
}
if (next==lastReturned)
next = lastNext;
else
nextIndex;
lastReturned = header;
expectedModCount++;
}
// 修改当前节点的内容
public void set(E e) {
if (lastReturned == header)
throw new IllegalStateException();
checkForComodification();
lastReturnedelement = e;
}
// 在当前持有节点后面插入新节点
public void add(E e) {
checkForComodification();
// 将最近一次返回节点修改为header
lastReturned = header;
addBefore(e next);
nextIndex++;
expectedModCount++;
}
// 判断expectedModCount和modCount是否一致以确保通过ListItr的修改操作正确的反映在LinkedList中
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
下面是一个ListItr的使用实例
LinkedList<String> list = new LinkedList<String>();
listadd(First);
listadd(Second);
listadd(Thrid);
Systemoutprintln(list);
ListIterator<String> itr = listlistIterator();
while (itrhasNext()) {
Systemoutprintln(itrnext());
}
try {
Systemoutprintln(itrnext());// throw Exception
} catch (Exception e) {
// TODO: handle exception
}
itr = listlistIterator();
Systemoutprintln(list);
Systemoutprintln(itrnext());
itradd(new node);
Systemoutprintln(list);
itradd(new node);
Systemoutprintln(list);
Systemoutprintln(itrnext());
itrset(modify node);
Systemoutprintln(list);
itrremove();
Systemoutprintln(list);
结果
[First Second Thrid]
First
Second
Thrid
[First Second Thrid]
First
[First new node Second Thrid]
[First new node new node Second Thrid]
Second
[First new node new node modify node Thrid]
[First new node new node Thrid]
LinkedList还有一个提供Iterator的方法descendingIterator()该方法返回一个DescendingIterator对象DescendingIterator是LinkedList的一个内部类
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
下面分析详细分析DescendingIterator类
private class DescendingIterator implements Iterator {
// 获取ListItr对象
final ListItr itr = new ListItr(size());
// hasNext其实是调用了itr的hasPrevious方法
public boolean hasNext() {
return itrhasPrevious();
}
// next()其实是调用了itr的previous方法
public E next() {
return itrprevious();
}
public void remove() {
itrremove();
}
}
从类名和上面的代码可以看出这是一个反向的Iterator代码很简单都是调用的ListItr类中的方法