Iterator中调用remove()前为什么必须先调用next()或previous()?

时间:2021-11-30
本文章向大家介绍Iterator中调用remove()前为什么必须先调用next()或previous()?,主要包括Iterator中调用remove()前为什么必须先调用next()或previous()?使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

关于Iterator,本文不再赘述,推荐阅读这篇文章

下面针对本文主题发表个人观点:

  • remove()方法删除的是上次return的element(通过lastRet控制)

    而Iterator提供了由前向后next()及从后向前previous()两种遍历方式,在无法确定遍历方式的情况下,remove()方法是无法确定要删除哪一个element的,因此需调用next()或previous()记录上次return element的index,即lastRet。

    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();
            }
        }
  • 至于游标cursor,记录的是next element index,而add()方法只能add element至下一个位置(由前向后)且add() 本身会维护cursor,因此add()之前无需调用next()或previous()。
        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

原文地址:https://www.cnblogs.com/jixiegongdi/p/15624797.html