现在的位置: 首页 > 综合 > 正文

ArrayList源代码分析

2018年02月01日 ⁄ 综合 ⁄ 共 2176字 ⁄ 字号 评论关闭

ArrayList 的底层实现是数组

 

1.构造函数

public ArrayList() {
    this(10);
}

public ArrayList(int initialCapacity) {
    super();//默认可以不写

        if (initialCapacity < 0)//初始化的容量如果小于0就抛出异常

            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);

    //创建一个大小为10的Object数据对象

    this.elementData = new Object[initialCapacity];

}

 

2. add函数

/**
     * 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) {
    ensureCapacity(size + 1);  // Increments modCount!!
    elementData[size++] = e;//将元素加到数组里面

    return true;
}

//minCapacity

public void ensureCapacity(int minCapacity) {
    modCount++;
    int oldCapacity = elementData.length;
    if (minCapacity > oldCapacity) {//如果超过范围

        Object oldData[] = elementData;
        int newCapacity = (oldCapacity * 3)/2 + 1;//增加容量为1.5倍加1

            if (newCapacity < minCapacity)
        newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);//把老的数组copy到新的数组中去

    }
}

 

3 get函数的方法

 /**
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
public E get(int index) {
    RangeCheck(index);//判断数组下标是否越界

    return (E) elementData[index];//通过下标得到元素然后返回

}

private void RangeCheck(int index) {
    if (index >= size)//如果越界就抛出异常

        throw new IndexOutOfBoundsException(
        "Index: "+index+", Size: "+size);
}

 

4.remove的函数

/**
     * 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 = (E) elementData[index];

    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,//自己copy给自己,就是移位

                 numMoved);
    elementData[--size] = null; // Let gc do its work

    return oldValue;
}

 

 

 

 

 

抱歉!评论已关闭.