zoukankan      html  css  js  c++  java
  • java foreach list.remove()一定会报错吗

    来两个例子热身。

            String[] arrays = {"1", "2", "3", "5" ,"4"};
            List<String> list = new ArrayList<>(Arrays.asList(arrays));
            for (String str : list) {
                //remove "1","2","3","4"会报错吗
                if (str.equals("1")) {
                    list.remove(str);
                }
            }
    

    答案:会

            String[] arrays = {"1", "2", "3", "5" ,"4"};
            List<String> list = new ArrayList<>(Arrays.asList(arrays));
            for (String str : list) {
                // remove "5"会报错吗?
                if (str.equals("5")) {
                    list.remove(str);
                }
            }
    

    答案: 不会

    但是不能在foreach里面这样做

    fastRemove 修改

     private void fastRemove(int index) {
            modCount++;
            int numMoved = size - index - 1;
            if (numMoved > 0)
                System.arraycopy(elementData, index+1, elementData, index,
                                 numMoved);
            elementData[--size] = null; // clear to let GC do its work
        }
    
    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
    

    public boolean hasNext() {
        return cursor != size;
    }
    
    public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }
    

    ArrayList总共有7种remove方法

    remove方法的时序图

        public boolean remove(Object o) {
            if (o == null) {
                // 找到为null的索引 i,然后remove(int i);
            } else {
                for (int index = 0; index < size; index++)
                    if (o.equals(elementData[index])) {
                        // 此处调用
                        fastRemove(index);
                        return true;
                    }
            }
            return false;
        }
    
  • 相关阅读:
    滴滴Ceph分布式存储系统优化之锁优化
    滴滴数据仓库指标体系建设实践
    滴滴AI Labs斩获国际机器翻译大赛中译英方向世界第三
    滴滴数据通道服务演进之路
    可编程网卡芯片在滴滴云网络的应用实践
    GPU虚拟机创建时间深度优化
    滴滴ElasticSearch千万级TPS写入性能翻倍技术剖析
    使用zip()并行迭代
    循环结构
    选择结构
  • 原文地址:https://www.cnblogs.com/bigorang/p/13158588.html
Copyright © 2011-2022 走看看