• 关于Iterator


    1.在迭代过程中,用list来删除元素的坑

     1 package test;
     2 
     3 import java.util.ArrayList;
     4 import java.util.Iterator;
     5 import java.util.List;
     6 
     7 public class IteratorTest {
     8 
     9     public static void main(String[] args) {
    10         List<String> list = new ArrayList<>();
    11         list.add("hello");
    12         list.add("world");
    13         list.add("helloworld");
    14 
    15         for(Iterator<String> i = list.iterator(); i.hasNext();) {
    16 
    17             /**
    18              * Iterator里有维护2个变量 cursor(表示当前的数组的索引值)、lastRet(表示上一个元素的索引值)
    19              * 就是说,迭代器获取值(next()方法)的时候,其实执行的就是list.get(cursor)
    20              *
    21              * 而arraylist里,维护了个变量——modCount,表示的是list的修改次数(增加、修改、删除的次数),
    22              * 在Iterator里,又维护了个变量——exoectedModCount,它的初始值就是list的modCount
    23              * 在Iterator的next()方法里,会检查modCount是否等于exoectedModCount,不相等,将抛出异常
    24              * 在调用了list.remove方法之后,modCount值加了1,但是没反映到Iterator,报错
    25              */
    26             String s = i.next(); // 第二次执行到这里的时候,会抛异常
    27             System.out.println(s);
    28 
    29             list.remove("helloworld");
    30         }
    31 
    32 
    33         List<String> list2 = new ArrayList<>();
    34         list2.add("hello");
    35         list2.add("world");
    36         list2.add("helloworld");
    37 
    38         for (int i = 0; i < list.size(); i++) {
    39             // 这里想删除全部元素,是错误的
    40             // 这里删除了元素以后,会影响list.size()的取值,list.size()会一直减小
    41             list.remove(i);
    42         }
    43 
    44     }
    45 
    46 }
  • 相关阅读:
    idea中yml文件变成text样式并且没有提示
    挂载redhat镜像创建本地yum源
    Windows环境下Oracle数据库的自动备份脚本
    Oracle存储过程锁表
    DDL和客户端ip监控
    Linux 单实例oracle安装步骤
    Linux常用命令
    Linux常用目录
    oracle基础知识及语法
    Linux下Oracle新建用户并且将已有的数据dmp文件导入到新建的用户下的操作流程
  • 原文地址:https://www.cnblogs.com/billmiao/p/9872183.html
Copyright © 2020-2023  润新知