共同学习Java源代码--数据结构--AbstractList抽象类(五)

    private class ListItr extends Itr implements ListIterator<E> 

这又是一个内部类。继承自上一个内部类,实现了ListIterator接口,这个是专门迭代List的迭代器、

        ListItr(int index) {
            cursor = index;
        }
首先是默认修饰符修饰的构造方法,将参数赋值给cursor变量。

        public boolean hasPrevious() {
            return cursor != 0;
        }
这个方法判断是否可以向前迭代,判断的依据就是cursor是否为0.

        public E previous() {
            checkForComodification();
            try {
                int i = cursor - 1;
                E previous = get(i);
                lastRet = cursor = i;
                return previous;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

这个方法返回上一个元素。首先判断两个modCount值是否相等。

然后创建变量i赋值为cursor减一,调用get方法获取上一个元素,将lastRet和cursor都赋值为i,最后返回上一个元素。如果此过程出现异常,先判断两个modCount是否同步,再抛出异常。

        public int nextIndex() {
            return cursor;
        }
这个方法获取的是下一个元素下标,就是cursor的值。

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

这个方法获取的是上一个元素下标,就是cursor的值减1。
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();


            try {
                AbstractList.this.set(lastRet, e);
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

这个方法是赋值的方法首先判断lastRet元素是否小于0,否则就抛异常,小于0代表刚刚删除过元素,还没有进行迭代。然后再检查两个modCount是否相等。

然后调用set方法赋值,为lastRet下标的元素赋值,然后将两个modCount同步。

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

        }

这个方法是添加元素的方法。首先检查两个modCount变量是否相等。

然后创建变量i赋值为cursor。然后调用add方法添加元素,添加的下标是i,然后lastRet赋值为-1,cursor赋值为i+1,最后将两个modCount同步。

如果此过程出现异常则抛出异常。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值