想到一个优化
–
`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的方法实现的。这是代理吗?