zoukankan      html  css  js  c++  java
  • 迭代器错误处理

    并发修改异常

    Exception in thread "main" java.util.ConcurrentModificationException

    具体原因:迭代器是依赖与集合的,相当于集合的一个副本,当迭代器在操作的时候,如果发现和集合不一样(元素个数),则输出异常

    public class InteratorDeom3 {
        public static void main(String[] args) {
            //method1();
            
            Collection c =new ArrayList();
            
            //List c =new ArrayList();
            c.add("hello");
            c.add("wold");
            c.add("java");
            
            //通过遍历获取集合中的每一个元素,然后进行比较即可
            Iterator it =c.iterator();
            while(it.hasNext()) {
                String s =(String)it.next();//转成字符串类型
                if(s.equals("java")) {
                    c.add("android");
                }
            }
        System.out.println(c);
        }

    处理:

    不使用迭代器
    在使用迭代器在进行遍历的时候使用迭代器来遍历

    使用第二种方法处理:

    public class InteratorDeom3 {
        public static void main(String[] args) {
            //method1();
            
            //Collection c =new ArrayList();
            
            List c =new ArrayList();
            c.add("hello");
            c.add("wold");
            c.add("java");
            
            //通过遍历获取集合中的每一个元素,然后进行比较即可
            /*Iterator it =c.iterator();
            while(it.hasNext()) {
                String s =(String)it.next();//转成字符串类型
                if(s.equals("java")) {
                    c.add("android");
                }
            }*/
            
            ListIterator Lit =c.listIterator();
            while(Lit.hasNext()) {
                String s =(String)Lit.next();//获取元素
                if(s.equals("java")) { //进行判断
                    Lit.add("android"); //使用迭代器去添加
            }
            
            System.out.println(c);
        }
  • 相关阅读:
    PHP header的几种用法
    Elasticsearch 学习笔记
    elsearch 安装过程中遇到的错误解决方式
    python常用模块
    python 列表和字段的相关函数
    Nginx+Redis+Ehcache大型高并发高可用三层架构总结
    Docker技术底层架构剖析
    ELK日志分析平台环境部署 (yum安装)
    禁止root直接登陆linux系统
    浅谈Rsync+Inotify实时同步
  • 原文地址:https://www.cnblogs.com/kun19/p/11062301.html
Copyright © 2011-2022 走看看