arrayList浅析
arrayList浅析
锦语冰 发表于11个月前
arrayList浅析
  • 发表于 11个月前
  • 阅读 0
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 十分钟定制你的第一个小程序>>>   

linkedList,以后再说

概述

arrayList是基于数组的。当知道数组的下标时,查找很快,当你不关心要插入的地方是否有值时,插入也很快。但数组大小有限,不易扩展,所以有了arrayList。(比hashMap简单得多,毕竟一个是纯链表(高级数组),一个是数组、链表、红黑树的组合)

属性

/**
 * Default initial capacity.
 */
private static final int DEFAULT_CAPACITY = 10;//默认初始大小  10

/**
 * Shared empty array instance used for empty instances.
 */
private static final Object[] EMPTY_ELEMENTDATA = {};//指定初始化大小为0时的数组,静态全局,避免每次都创建

/**
 * 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 = {};//未设置初始大小时的数组

/**
 * 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];//在构造时,就初始化数组,hashMap是在put时才初始化
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * 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;
        }
    }

  add方法,太简单,不值得细讲

public boolean add(E e) {//纯粹的插在最后,不具备修改的语义
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}
private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//调用了无参构造函数
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);//单线程下,minCapacity最终为10,ArrayList非线程安全
    }

    ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
    modCount++;//不要在for(? : ?List)循环里修改,会有异常。可用迭代器、CORList代替

    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);//新容量约为原来的1.5倍(扩容一半)
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)             //MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}

大底上add,remove,最后都会调用System.array...(....),比较简单。arrayList的底层毕竟是数组,所以不会太复杂。

有一点要注意,批量删除时,从尾部开始删

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);//性能消耗的关键在于此,删除一个元素时,为了保持数组的连续,要对数组进行移动
                                       //举两个极端的例子,listA每次remove(0),要移动size-1个元素; listB每次remove(size-1),移动0个元素
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

 

共有 人打赏支持
粉丝 3
博文 34
码字总数 31315
×
锦语冰
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: