• Collection并发问题分析与解决


    最近面试被问了一个很nice的问题,collection遍历操作删除元素,有几种方式。自己的求知不怎么高,以至于只知道个大概,今天抽空详细了解并分析一下原因,顺便分享一下有哪些。

            ArrayList<String> strLs = new ArrayList<>();
            strLs.add("stone1");
            strLs.add("stone2");
            strLs.add("stone3");
            strLs.add("stone4");
            strLs.add("stone5");
    
    //      因为遍历的时候,删除了一个元素,所以后续的元素的索引相对于以前的索引-1了
            for (int i = 0; i < strLs.size(); i++) {
                String temp = strLs.get(i);
                if (temp.equals("stone3")){
                    strLs.remove("stone3");
                    i--;
                    continue;
                }
                System.out.println(temp);
            }
    
    //      数组反向遍历,删除中间的数组,前面的索引还是不会改变的
            for (int i = strLs.size() - 1; i >= 0; i--) {
                String temp = strLs.get(i);
                if (temp.equals("stone3")){
                    strLs.remove("stone3");
                    continue;
                }
                System.out.println(temp);
            }
    
    //        以上的问题是因为通过改变数组的大小,而造成所以可能变化,当用迭代器就不会有这中问题
            Iterator<String> iterator = strLs.iterator();
            while (iterator.hasNext()){
                String next = iterator.next();
                if (next.equals("stone3"))
                    iterator.remove();
                else
                    System.out.println(next);
            }
        }
    
  • 相关阅读:
    JQuery实现页面跳转
    CSS中让背景图片居中且不平铺
    C#后台将string="23.00"转换成int类型
    BootStrap的一些基本语法
    CSS实现文字阴影的效果
    BootStrap自定义轮播图播放速度
    BootStrap 轮播插件(carousel)支持左右手势滑动的方法(三种)
    C#常用快捷键
    jQuery hover() 方法
    鼠标移动有尾巴
  • 原文地址:https://www.cnblogs.com/theStone/p/16017686.html
Copyright © 2020-2023  润新知