ListItr的实现

最近,我发现我对java集合中迭代器的实现很感兴趣。昨天看完AbstractList中的Itr的实现后,觉得很有意思,今天索性就把ListItr看完。

ListItr

private class ListItr extends Itr implements ListIterator<E>

他继承了Itr同时又实现了ListIterator接口,看下ListIterator接口的定义

boolean hasNext();
    E next();
    boolean hasPrevious();
    E previous();
    int nextIndex();
    int previousIndex();
    void remove();
    void set(E e);
    void add(E e);
总共9个方法。光看方法名就知道他们的功能了。我们赶紧去看ListItr如何实现他们的吧。


hasPrevious

public boolean hasPrevious() {
            return cursor != 0;
        }
只要判断下游标是否等于0就可以判断他是否有前一个元素。


previousIndex

public int previousIndex() {
            return cursor-1;
        }
实现也非常简单。


nextIndex

public int nextIndex() {
            return cursor;
        }
返回游标的值。


set

public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                AbstractList.this.set(lastRet, e);//调用AbstractList的set方法
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

看过代码后,没什么感想。

add

public void add(E e) {
            checkForComodification();//安全

            try {
                int i = cursor;
                AbstractList.this.add(i, e);//多态
                lastRet = -1;
                cursor = i + 1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
这种面对抽象编程的思想已经深入代码的骨子里了,高手就高手呀!


转载于:https://my.oschina.net/tunie/blog/121687

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值