首页 > 其他 > 详细

LinkedList的Iterator()方法理解

时间:2019-12-16 14:39:55      阅读:229      评论:0      收藏:0      [点我收藏+]
LinkedList有两种迭代器实现,均使用内部变量next进行数据迭代
1. LinkedList.iterator()迭代方法很好体现了java实现的继承回调机制
LinkedList本身没有iterator()方法,使用其抽象父类AbstractSequentialList<E>的iterator()方法,其中调用的listIterator()方法又是继承自上一级AbstractList<E>父类;最后在listIterator()方法中调用了listIterator(0)方法,而此方法又被LinkedList本身实现,进而回调到该方法上。
public ListIterator<E> listIterator(int index) {  // 继承回调该方法
checkPositionIndex(index);
return new ListItr(index);
}

private class ListItr implements ListIterator<E> {
private Node<E> lastReturned; // 使用node节点查找并缓存数据
private Node<E> next;
private int nextIndex; // 是否遍历结束
private int expectedModCount = modCount;

ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}

public boolean hasNext() {
return nextIndex < size;
}

public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();

lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}

public boolean hasPrevious() {
return nextIndex > 0;
}

public E previous() { // 支持前后两种遍历方法
checkForComodification();
if (!hasPrevious())
throw new NoSuchElementException();

lastReturned = next = (next == null) ? last : next.prev;
nextIndex--;
return lastReturned.item;
}

public int nextIndex() {
return nextIndex;
}

public int previousIndex() {
return nextIndex - 1;
}

public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();

Node<E> lastNext = lastReturned.next;
unlink(lastReturned);
if (next == lastReturned)
next = lastNext;
else
nextIndex--;
lastReturned = null;
expectedModCount++;
}

public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}

public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}

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();
}

final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
2. LinkedList的descendingIterator()方法,是对第一种迭代类的倒序封装,且只支持倒序遍历
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}

private class DescendingIterator implements Iterator<E> {
private final ListItr itr = new ListItr(size());
public boolean hasNext() {
return itr.hasPrevious();
}
public E next() {
return itr.previous();
}
public void remove() {
itr.remove();
}
}

LinkedList的Iterator()方法理解

原文:https://www.cnblogs.com/septemberFrost/p/12047861.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!