为什么Iterator要先next再remove


在使用iterator的时候为什么要先next再remove不然就会抛错呢

@org.junit.Test

public void testArrayList(){
ArrayList <Integer>list =new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
Iterator<?> it=list.iterator();
System.out.println(list);
while(it.hasNext()){
it.next();
it.remove();
System.out.println(list);
}

}


看一下jdk的实现

 private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return  这个是next之后的位置坐标,初始值是0,JVM的初始化
        int lastRet = -1; // index of last element returned; -1 if no such 这个是next之前的位置坐标
        int expectedModCount = modCount; //这个是list集合的大小


        public boolean hasNext() {
            return cursor != size;//next以前的位置,从0开始
        }


        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;//获得list内部的元素
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;//将位置推进1
            return (E) elementData[lastRet = i];//记录下当前的位置  比如是0的时候  lastRet =0 lastRet =1
        }


        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();


            try {
                ArrayList.this.remove(lastRet); //删除前一个元素
                cursor = lastRet; //将指针回退
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }


        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

可以看得出来如果直接调用remove lastRet =-1 所以直接抛错 throw new IllegalStateException();.这么做的好处其实可以控制遍历时候数组越界提升性能,其中匠心得要细细的品味



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值