美文网首页
ArrayList 动态数组

ArrayList 动态数组

作者: siyanGo | 来源:发表于2017-04-17 16:19 被阅读43次
/**
     * Default initial capacity.
     * 数组的默认初始大小
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 
     *这里定义了两个相同的object数组 区别是 DEFAULTCAPACITY_EMPTY_ELEMENTDATA数组知道扩大多少当第一个元素放入时
     *
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     *  数组缓冲区 存储元素就是这个,他的大小就是ArrayList大小,每一个空的数组
     *  当elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA在插入第一个元素的时候就会扩大到DEFAULT_CAPACITY
     *
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;


    /**
     * 
     * 制定构造初始大小   
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**这里用的是 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 说是初始为10 ensureCapacityInternal()在这里看
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    /**
    *当ArrayList由ArrayList()构造的时候 如果size小于10 最小容量设置为10
    *
    */

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }


    /*
    *
    *  判断是否需要grow 当最小容量大于ArrayList容量是时增长
    *
    */

      private void ensureExplicitCapacity(int minCapacity) {
       
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }


    /**
    *   new = old + old /2
    *   old=size+1
    *   new=size+(size+1)/2
    *   new=1.5size;
    *   新数组增长为原来的1.5倍
    *   还判断了超出了Integer 最大值
    *   
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            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);
    }




     /**
     * ps:Arrays.copyOf()不仅仅只是拷贝数组中的元素,在拷贝元素时,会创建一个新的数组对象。而System.arrayCopy只拷贝已经存在数组元素。
     *remove 的时候是对自身进行copy,没有新的数组操作
     * 然后GC执行工作
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        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

        return oldValue;
    }


     /**
     *
     *首先检测是否越界
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

相关文章

  • 关于ArrayList

    ArrayList简介 ArrayList内部是以动态数组存放数据的,所谓动态数组,不是数组本身可以改变长度,而是...

  • ArrayList 与 LinkedList 列表结构分析

    ArrayList ArrayList 内部维护了一个动态的Object 数组,ArrayList 的动态增删就是...

  • ArrayList源码解析

    ArrayList简介 ArrayList底层是数组队列,相当于动态数组。与java中的数组相比,它的长度能动态增...

  • ArrayList学习笔记

    ArrayList--动态数组 ArrayList介绍: 从源码分析: 遍历方式:

  • Java数据结构(2)ArrayList

    ArrayList ArrayList 是一个数组队列,相当于 动态数组,与数组相比,它的容量能动态增长。 和Ve...

  • Java集合——ArrayList

    简介ArrayList实际上是动态数组,它提供动态增删元素的方法,数组大小可以灵活设置,但是ArrayList不是...

  • ArrayList的使用及ConcurrentModificat

    ArrayList是一种动态数组,可以动态的增加或删除元素。ArrayList和Vector都是用数组实现的,但二...

  • Java主要数据结构总结

    数组线性表类ArrayList 和链表类LinkedList ArrayList用数组存储元素,这个数组是动态创建...

  • Java基础day08ArrayList和继承

    ArrayList 类 对象数组 数组长度是固定, 无动态扩容 java.util.ArrayList 集合类,更...

  • java基础—浅析ArrayList源码

    ArrayList简介 ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态...

网友评论

      本文标题:ArrayList 动态数组

      本文链接:https://www.haomeiwen.com/subject/cgbtzttx.html