Java数据结构:ArrayList源码分析

ArrayList简介

ArrayList数据java中比较基本,简单,常用的一种数据结构,

属于几大数据结构中的线性数据结构,拥有线性数据结构特点。

分析一:ArrayList实质结构

打开arrayList源码可以看见

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] 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 == EMPTY_ELEMENTDATA will be expanded to
     * DEFAULT_CAPACITY when the first element is added.
     */
    private transient Object[] elementData;

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

实质上 arrayList内部就是一个Object[]数组,初始容量 DEFAULT_CAPACITY=10 ,成员变量 size 为arrayList的长度,后面会发现

size并不是数组elementData的真实长度

分析二:ArrayList构造函数

不难发现ArrayList拥有3个构造函数

构造一:

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        super();
        this.elementData = EMPTY_ELEMENTDATA;
    }

没有参数,直接使用赋值一个空数据数组

构造二:

    /**
     * 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) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }

参数:数组长度  创建一个规定长度的数组

构造三:

   /**
     * 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();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

参数:集合   直接将参数集合进行 toArray 然后赋值给 数组elementData 

PS:本人曾经没有分析过源码,每次要构建一个新的newArrayList并且需要旧的oldArrayList里面数据

使用过以下方案

ArrayList<String> oldArrayList = new ArrayList<>();

oldArrayList.add("数据");

...

...

方案一 : 

ArrayList<String> newArrayList = oldArrayList 

这种方法赋值,按C/C++方法来说就是指针地址的赋值,按java来讲newArrayList只是OldArrayList的引用,

如果我们改变newArrayList里面的数据,那么oldArrayList也会跟着改变,

跟我想要的 原数据不变 相冲突  ---  pass

方案二:

ArrayList<String> newArrayList = new ArrayList<>();

newArrayList.addAll(oldArrayList);

这种方法确实能达到我想到的需求,任意修改newArrayList数据,保持原数据不变

虽说这种方法实现过程只有两行代码,但实现过程,它会经过一次构造,一次addAll(关于addAll后面会讲到)

从性能说,不推荐

方案三:(最终方案,我能想到的)

ArrayList<String> newArrayList = new ArrayList<>(oldArrayList);

这种方法只需要调用构造方法就可以实现需求,且简单,性能上来说也比较好

分析三:ArrayList内部扩容方法

    /**
     * Increases the capacity of this <tt>ArrayList</tt> instance, if
     * necessary, to ensure that it can hold at least the number of elements
     * specified by the minimum capacity argument.
     *
     * @param   minCapacity   the desired minimum capacity
     */
    public void ensureCapacity(int minCapacity) {//提供给外部调用的方法
        int minExpand = (elementData != EMPTY_ELEMENTDATA)
            // any size if real element table
            ? 0
            // larger than default for empty table. It's already supposed to be
            // at default size.
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }
    // minCapacity:需要扩容量 
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == EMPTY_ELEMENTDATA) {//判断当前数组是否为空
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); //取默认大小和需要扩容量 的最大值 来进行扩容
        }

        ensureExplicitCapacity(minCapacity);
    }

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

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

    /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 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); //新的容量 = 旧的容量+ 0.5*旧的容量(旧的容量右移一位)=1.5旧的容量
        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);    //调用 数组扩容方法 
    }

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

综合 上面 : arrayList 扩容跟数组扩容一样 

分析四:Arraylist的增删改查(重点)

ArrayList :

第一种 函数 : 直接增加一个元素 

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

示例图 


假设示例图中 一 没有添加元素前 数组有 5个元素 容量 为 5 

             图中 二 将elementData数组增加容量 最后容量为 5 + 5>>1 = 7

             图中 三 将新元素e赋值到第六个位置下标为5 , 并且将数组长度size +1 

这就是arrayList 添加 一个元素 所要 处理的所以过程

第二种 函数 : 在某个位置增加一个元素 

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

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

示例图


假设示例,需要在下标index = 3的位置添加一个元素

             图中 一 没有添加元素前 数组有 5个元素 容量 为 5 

             图中 二 为扩容分配的内存地址新增容量 最后容量为 5 + 5>>1 = 7

             图中 三 将新的elementData数组下标index的位置 长度 size - index=2  的数据copy到 数组下标index+1的位置

             图中 四 将新元素e赋值到第四个位置下标index=3 , 并且将数组长度size +1 

这就是arrayList 在某个位置添加一个元素 所要 处理的所以过程

函数三 : 直接添加一个集合

    /**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the
     * specified collection's Iterator.  The behavior of this operation is
     * undefined if the specified collection is modified while the operation
     * is in progress.  (This implies that the behavior of this call is
     * undefined if the specified collection is this list, and this
     * list is nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    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;
    }

示例图


假设示例  旧的old  ,  需要添加的addList

            图中 一 没有添加元素前 数组有 5个元素 容量 为 5 

            图中 二 将elementData数组增加容量size+numNew = 10

            图中 三 将新元素addList copy到 数组old 组成新的数组  arrayList长度 变成 size+numNew

这是直接添加一个list集合 过程

函数四 : 在某个下标开始添加一个集合

    /**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     *
     * @param index index at which to insert the first element from the
     *              specified collection
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(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;
    }

示例图


假设示例  旧的old  ,  需要添加的addList  要将index=3的位置插入addList

            图中 一 没有添加元素前 数组有 5个元素 容量 为 5 

            图中 二 将elementData数组增加容量size+numNew = 10

            图中 三 将扩容后的elementData中元素从index=3开始长度为2,目标位置index+numNew开始copy到数组中

            图中 四 将新元素addList 在下标index位置开始copy到 数组old 组成新的数组  arrayList长度 变成 size+numNew


ArrayList : 删

函数一 : 

    /**
     * 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) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        modCount++;
        E oldValue = (E) 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;
    }

示例图



假设示例,需要移除下标index = 2的位置的元素

             图中 一 数组有 5个元素 容量 为 5 

             图中 二 将3,4copy并左移

             图中 三 将新的elementData数组最后一个元素置null,最后 将arraylist长度 size-1

这就是arrayList移除某个位置元素 所要 处理的所以过程

函数二 :

    /**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If the list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * <tt>i</tt> such that
     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

删除指定元素,从注释也能看出来,是删除arrayList出现第一个这个元素,代码很简单,遍历,比对元素相等,然后调用函数一删除这个下标元素

ArrayList : 改

函数 : 

    /**
     * Replaces the element at the specified position in this list with
     * the specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        E oldValue = (E) elementData[index];
        elementData[index] = element;
        return oldValue;
    }

修改某个元素 很简单 就把对应下标数组里面的值替换掉,就可以了

ArrayList : 查

函数:

    /**
     * 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) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        return (E) elementData[index];
    }

查询某个下标位置元素,也很简单,就是 返回 数组对应下标元素

总结

上面我们从源码分析了ArrayList中的构造函数,以及基本的增删改查,本质来说就是在操作数组,需要注意的是ArrayList的长度size是数组elementData的中非空元素的长度。从增删改查中看出,arrayList 增加删除远远比查询和修改的效率要低

最好,希望大佬们点评,指正,互相进步

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值