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

  简单的学习下

 

posted on 2018-04-17 21:49  爱不死  阅读(1088)  评论(0编辑  收藏  举报