zoukankan      html  css  js  c++  java
  • 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();
                }
            }
  • 相关阅读:
    oracle10G/11G官方迅雷下载地址合集(转载)
    Oracle数据库的登录以及常用数据导入查询
    Tomcat添加SSL网站证书配置
    SVN的安装与在IDEA中的配置
    01-Spring Boot配置文件详解
    微服务概况及注册中心搭建
    zk实现分布式锁
    ZooKeeper初识
    Reids集群知识
    redis初识
  • 原文地址:https://www.cnblogs.com/jixiegongdi/p/15624797.html
Copyright © 2011-2022 走看看