JDK 1.8 LinkedList中双向迭代器实现细节小记

在学习LinkedList源码时,发现对它的内部迭代器ListItr的实现有几个函数费了一番脑筋,记录下来供以后复习使用。这几个函数是next()、previous()以及remove()。

先把它们的源码贴上来:

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

            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.item;
        }
public E previous() {
            checkForComodification();
            if (!hasPrevious())
                throw new NoSuchElementException();


            lastReturned = next = (next == null) ? last : next.prev;
            nextIndex--;
            return lastReturned.item;
        }
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++;
        }
next比较直观,next后移一位,lastReturned位于next之前。而previous在执行后,lastReturned与next相等了。这样就导致在remove操作中删除掉lastReturned结点后,需要增加一次判断。若上一次操作是previous(),则此时删除lastReturned后,next也会“悬空”,需要将其指向lastNext。若上一次操作是next(),则删除lastReturned时next结点不会受到影响。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值