首页 > 其他 > 详细

迭代器错误处理

时间:2019-06-21 09:04:26      阅读:88      评论:0      收藏:0      [点我收藏+]

并发修改异常

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);
    }

 

迭代器错误处理

原文:https://www.cnblogs.com/kun19/p/11062301.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!