想到一個優化
–
`if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}`
要是給鏈表分別插入一個虛擬的頭結點和尾節點,就不用每次這樣判斷了所有操作都可以看成是鏈表內的操作,豈不是美滋滋。
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;
}
優化從前面開始找,還是從後面開始找。
從這個代碼可以看出來,鏈表的編號是從0開始的。
java子類直接屏蔽父類的同名變量。
iterator
和 listiterator
的區別
http://stackoverflow.com/questions/10977992/difference-between-iterator-and-listiterator
List的iterator方法
public Iterator<E> iterator() {
return listIterator();
}
public ListIterator<E> listIterator() {
return listIterator(0);
}
public ListIterator<E> listIterator(final int index) {
checkForComodification();
rangeCheckForAdd(index);
return new ListIterator<E>() {
private final ListIterator<E> i = l.listIterator(index+offset);
public boolean hasNext() {
.........
..........
};
}
其實是獲取了是獲取了ListIterator然後進行了向上轉型。
previous()的實現效果
public static void main(String[] args){
LinkedList<Integer> list=new LinkedList<Integer>();
for (int i=0;i<9;i++){
list.add(i);
}
ListIterator<Integer> li=list.listIterator();
// while (li.hasNext()){
// System.out.println(li.next());
// }
for (int i=0;i<4;i++){
System.out.println(li.next());
};
System.out.println(li.previous());
System.out.println(li.previous());
System.out.println(li.next());
System.out.println(li.next());
}
output:
0
1
2
3
3
2
2
3
感覺next()和previces()這兩個函數的效果與含義不相符,既然已經輸出了3那麼previces()應該是2,previces()是2了那next()又是2??
找到一個解釋:
E next()
Returns the next element in the list. This method may be called repeatedly
previous to go back and forth. (Note that alternating calls to next and previous will return the same element repeatedly.)
http://stackoverflow.com/questions/15598297/listiterator-next-and-previous-detail
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (modCount == expectedModCount && nextIndex < size) {
action.accept(next.item);
lastReturned = next;
next = next.next;
nextIndex++;
}
checkForComodification();
}
這是迭代器中的一個方法,意思是講當前位置以後的元素都處理一遍,其中Consumer<? super E> action的? super E指的是E的父類,而Consumer是一個函數借口FI,FI主要是爲了支持Lambda表達式。
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
由於Iterator只能是單向的,而List是雙向的所以實現了兩個Iterator,這個反向的Iterator是調用ListItr的方法實現的。這是代理嗎?