LinkedList 源码小解
一、成员
private transient Entry<E> header = new Entry<E>(null, null, null);
private transient int size = 0;
底层维护的是一个Entry链表(双向循环链表)
二、LinkedList.Entry类
成员
E element; //data
Entry<E> next; //前指针
Entry<E> previous; //后指针
三、方法
1、
public LinkedList() {
header.next = header.previous = header;
}
该方法构造了一个新的Entry链表,前后指针都指向自身
2、
public E getFirst() {
if (size==0)
throw new NoSuchElementException();
return header.next.element;
}
获取链表中第一个元素
3、
public E getLast() {
if (size==0)
throw new NoSuchElementException();
return header.previous.element;
}
获取链表中最后一个元素
4、
private E remove(Entry<E> e) {
if (e == header)
throw new NoSuchElementException();
E result = e.element;
e.previous.next = e.next;
e.next.previous = e.previous;
e.next = e.previous = null;
e.element = null;
size--;
modCount++;
return result;
}
移除链表中的某个元素
5、
private Entry<E> addBefore(E e, Entry<E> entry) {
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size++;
modCount++;
return newEntry;
}
插入一个元素
6、
public boolean addAll(int index, Collection<? extends E> c) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew==0)
return false;
modCount++;
Entry<E> successor = (index==size ? header : entry(index));
Entry<E> predecessor = successor.previous;
for (int i=0; i<numNew; i++) {
Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
predecessor.next = e;
predecessor = e;
}
successor.previous = predecessor;
size += numNew;
return true;
}
在链表最后面添加
7、
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;
}
获得index对应的Entry对象,如果index>size>>1则使用前指针,如果index<size>>1 则使用后指针遍历到索引处
8、
public int indexOf(Object o) {
int index = 0;
if (o==null) {
for (Entry e = header.next; e != header; e = e.next) {
if (e.element==null)
return index;
index++;
}
} else {
for (Entry e = header.next; e != header; e = e.next) {
if (o.equals(e.element))
return index;
index++;
}
}
return -1;
}
获取元素对应的索引位置
9、
public boolean removeLastOccurrence(Object o) {
if (o==null) {
for (Entry<E> e = header.previous; e != header; e = e.previous) {
if (e.element==null) {
remove(e);
return true;
}
}
} else {
for (Entry<E> e = header.previous; e != header; e = e.previous) {
if (o.equals(e.element)) {
remove(e);
return true;
}
}
}
return false;
}
移除最后一次出现的元素
10、
private class ListItr implements ListIterator<E>
list中用来遍历的iterator类型
11、
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
private class DescendingIterator implements Iterator
用于倒序遍历的iterator