ArrayList源码(1)

ArrayList继承了AbstractList并实现了List接口。
三种初始化的方法:

第一种:规定List长度的参数
public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }
第二种:无参数,默认长度10    
public ArrayList() {
        this(10);
    }
第三种:类似复制一个List
//List<String> list = new ArrayList<String>();
//list.add("1");
//List<String> list2 = new ArrayList<String>(list);
public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

三种创建List的方法最后都是将数据存储到elementData里面,它的定义在源码中

private transient Object[] elementData;

transient的解释在之前文章中说过了。
接着我们从我们平时经常使用的方法来说其中的源码。
在ArrayList先要用的肯定是add()方法了:

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

public void add(int index, E element) {
    rangeCheckForAdd(index);

    ensureCapacityInternal(size + 1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);
    elementData[index] = element;
    size++;
}

两个公共的方法也是重要的方法ensureCapacityInternal(size + 1); 这个一看应用也应该知道是向List后添加新的扩展。

private void ensureCapacityInternal(int minCapacity) {
    modCount++;
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

其中modCount也是定义为transient类型的参数,并继承自父类AbstractList。这个参数的作用在之后的文章再进行说明,因为他在List,Map等多个里面都有应用(如果之后我没有这个说明博客的话请大家提醒)。
之后进行判断增加一个之后List的容量是否能够存储,如果不够存储的话进行grow(min…)方法进行扩容(扩50%)。

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

扩容50%int newCapacity = oldCapacity + (oldCapacity >> 1); >> 快速进行计算。
判断如果扩容后的大小还是比要求存储的数量小的话直接newCapacity = minCapacity;如果扩容后的大小比MAX_VALUE-8还要大的话进行hugeCapacity(minCapacity)方法。

private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

最大的容量也就是Integer.MAX_VALUE。
扩容后执行 Arrays的复制方法:

public static <T> T[] copyOf(T[] original, int newLength) {
    return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    T[] copy = ((Object)newType == (Object)Object[].class)
        ? (T[]) new Object[newLength]
        : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}

之后的源码也没有什么内容了。
扩容后将新增的内容添加到size++的位置elementData[size++] = e;新增完毕。
在指定的位置增加内容就是多了两个方法

/**
 * A version of rangeCheck used by add and addAll.
 * 判断index位置是否正确
 */
private void rangeCheckForAdd(int index) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//将List位置空出,将之后的数据向后移动
public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

基本的新增源码是这些,还有两个addAll的方法:

public boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityInternal(size + numNew);  // Increments modCount
    System.arraycopy(a, 0, elementData, size, numNew);
    size += numNew;
    return numNew != 0;
}

public boolean addAll(int index, Collection<? extends E> c) {
    rangeCheckForAdd(index);

    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityInternal(size + numNew);  // Increments modCount

    int numMoved = size - index;
    if (numMoved > 0)
        System.arraycopy(elementData, index, elementData, index + numNew,
                         numMoved);

    System.arraycopy(a, 0, elementData, index, numNew);
    size += numNew;
    return numNew != 0;
}

在addAll里面的方法也是那几个,主要多的内容就是将以前的数组转换成Object[] a = c.toArray();然后扩容,再System.arraycopy(a, 0, elementData, size, numNew);将内容放进去就可以了。在指定位置添加也是这个样子。
之后文章再看其他方法的源码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值