接上文 - java 集合类-ArrayList
LinkedList的底层实现方法:双向链表。
LinkedList用静态内部类Entry来表示一个节点,定义一个 header节点。
Entry内部定义了 前驱节点和后驱节点 以及存储数据。
LinkedList 源码:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Queue<E>, Cloneable, java.io.Serializable
{
private transient Entry<E> header = new Entry<E>(null, null, null);
private transient int size = 0;
/**
* Constructs an empty list.
*/
public LinkedList() {
header.next = header.previous = header;
}
内部类 Entry 源码:
private static class Entry<E> {
E element;
Entry<E> next; //后置节点
Entry<E> previous;//前驱节点
Entry(E element, Entry<E> next, Entry<E> previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}
LinkedList add方法源码 :
public boolean add(E o) {
addBefore(o, header);
return true;
}
//将新添的数据增加到链表模型中,参考下图。
private Entry<E> addBefore(E o, Entry<E> e) {
Entry<E> newEntry = new Entry<E>(o, e, e.previous);
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size++;
modCount++;
return newEntry;
}
增加后双向链表的数据模型如下:
LinkedList get方法源码:
public E get(int index) {
return entry(index).element;
}
//找到对应的Entry对象。
private Entry<E> entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> e = header;
//index 与 size/2 进行比较 确定前驱查找或是后驱查找
//具体查找可参考上图模型。
//如若 size > 10, index=1 ,
//则查找对象相当于 Entry e = header.next.next;
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}
LinkedList 删除方法源码:
public E remove(int index) {
return remove(entry(index));
}
private Entry<E> entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> e = header;
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}
private E remove(Entry<E> e) {
if (e == header)
throw new NoSuchElementException();
E result = e.element;
//关联删除节点左右两边的节点
//如上图:若删除第一个节点,则将header与第二个节点相互关联上即可。
e.previous.next = e.next;
e.next.previous = e.previous;
e.next = e.previous = null;
e.element = null;
size--;
modCount++;
return result;
}