ArrayList源代码分析

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

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值