• Arraylist JDk1.8扩容和遍历


    Arraylist作为最简单的集合,需要熟悉一点,记录一下---->这边主要是注意一下扩容和遍历的过程

    请看以下代码

      public static void main(String[] args) {
    
            List<String> list = new ArrayList<String>();
            list.add("a");
            list.add("b");
            list.add("c");
            list.add("d");
            list.add("e");
            list.add("f");
            Iterator iterator = list.iterator();
            while(iterator.hasNext()){
                String str = (String) iterator.next();
                if(str.equals("a")){
                    list.remove(str);
                }else{
                    System.out.println(str);
                }
            }
        }

    执行结果 发生了异常!for遍历的时候进行删除和添加操作,也会出现异常!

    这是因为

    Iterator遍历的时候 fail-fast的检查机制
       private class Itr implements Iterator<E> {
            int cursor;       // index of next element to return
            int lastRet = -1; // index of last element returned; -1 if no such
            int expectedModCount = modCount;//每次add或remove 都会增加1(有点类似于记录改变集合数据的行为),遍历的时候初始化
    
            public boolean hasNext() {
                return cursor != size;
            }
    
            @SuppressWarnings("unchecked")
            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];
            }
    
      final void checkForComodification() {
                if (modCount != expectedModCount)//判断是否相等
                    throw new ConcurrentModificationException();
            }
        }

    扩容问题,其实也很简单

       private void grow(int minCapacity) {
            // overflow-conscious code
            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            if (newCapacity - minCapacity < 0)//这边当oldCapacity大到一定程度的时候,向右移动会变成很大的负数,所以才有这个判断
                newCapacity = minCapacity;
            if (newCapacity - MAX_ARRAY_SIZE > 0)
                newCapacity = hugeCapacity(minCapacity);
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
    

      简单的学习下

  • 相关阅读:
    appfabric cache配置,实验记录
    appfabric cache存储ef 查询结果的bug
    CruiseControl.NET svn获取 自动编译 ftp上传
    @Ajax.RenderAction 把局部页改为ajax加载
    分布式架构下的mvc 异步controller ajax comet 长连接
    win7重装iis,搞死
    验证码识别的基本思路及方法
    C# 获取程序当前文件夹
    在c#中 限制文本框只能输入数字
    string字符串 获取指定位置范围的子字符串
  • 原文地址:https://www.cnblogs.com/jinjian91/p/8870247.html
Copyright © 2020-2023  润新知