java集合之ArrayList源码解读 帮助大家自己动手写一个ArrayList

java集合之ArrayList源码解读 帮助大家自己动手写一个ArrayList


一、我们知道ArrayList与一般数组最明显的区别是ArrayList可以存放不同类型的数据,而数组只能存放相同类型的数据。
下面我们来看一下ArrayList底层原理的实现
/**
     * 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

观察这段源码,我们可以知道原来ArrayList是使用Object数组来存放数据的呀!原来本质还是数组。
二、下面通过我们使用ArrayList的过程,将ArrayList的实现原理一一进行解析,最后解析完,大家能够很轻松的写一个自己的简化版ArrayList,我的目的也就达成了。
1、首先我们要new一个ArrayList对象,当然通过反射也行,这里只说最常见的情形。
下面展示ArrayList构造方法底层原理的实现,当然构造方法很多,在这里只展示无参和带大小参数的构造函数,感觉是最具代表性。
/**
     * 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 = {};
1)无参数的构造函数
/**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
2)带大小参数的构造函数
/**
     * 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];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
通过构造函数我们可以知道,其实new一个ArrayList对象就是给elementData这个对象数组进行初始化的过程。
2、有了ArrayList对象之后,我们就要往里面存放我们的数据了。
这里AarryList使用的是add方法,下面展示源码,并分析算法实现原理,同样add方法重载的版本很多,在此也只介绍最常见的
/**
     * A version of rangeCheck used by add and addAll.
     */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }
/**
     * 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;
    }
/**
     * 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) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
算法思想也比较简单
实现原理是:
(1) 首先判断初始容量是否足够,如果不足够,进行扩容
(2) 在容量足够的情况下,存放数组
当然上述只是大致原理,还有很多细节需要完善。例如,边界判断,扩容算法等等。当然对于写一个简单的add方法这些就足够了。详细可以参照源码。

3、有了一个存放了我们需要数据的ArrayList的容器,下面我们要做的就是如何从中获取我们所需要的数据了。
这里我们展示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) {
        rangeCheck(index);

        return elementData(index);
    }
通过源码我们进一步可以知道,ArrayList的底层实现就是数组,这里ArrayList获取数据就是通过数组索引进行获取的。搞清楚了原理之后,这些原来这么简单,一点都不难。
4、在说一个非常简单的方法,获取ArrayList容器的大小。
不用我贴源码,我想大家已经知道怎么实现了。
/**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;
/**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
    public int size() {
        return size;
    }
是不是非常简单,在ArrayList中,我们会用一个int变量保存容器的大小,获取时,只需返回就行。如果要问我怎么保存的,我的回答是在上面的add方法中,就可以看到我们在增加数据时,对应的类成员变量size也会进行动态的变化。当然下面要讲的remove方法也是一样,它也会动态的更新类成员变量size的值。如果还是不太清楚,可以先继续往下学习,多体会体会就明白了。
5、有增加就会有删除,下面要说的就是删除容器的数据了。
在jdk1.8的源码中使用的时remove方法,下面展示源码
/*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     */
    private void fastRemove(int index) {
        modCount++;
        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
    }


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

/**
     * 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;
    }
是不是感觉有点复杂,确实是很复杂,但是那是在考虑了很多方面的情况下,我们的目的是为了弄清原理,所以只需要把握住最核心的部分就可以了。
我把核心代码粘贴出来
 for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }


/*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     */
    private void fastRemove(int index) {
        modCount++;
        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
    }

这里再次强调ArrayList的底层实现是数组!!!
算法实现原理:
(1) 首先找到要删除的元素的下标
(2) 之后将该下标之后所有数据全部向前移动一位。
(3) 回收数据,更新容器的大小,使用elementData[--size] = null;
6、类似数据库的crud,最后再讲一下如何修改容器中的数据。
这里再再次强调ArrayList的底层实现是数组!!!
相信大家不用看我下面的代码就已经知道怎么写了吧!下面我就只粘贴一个非常具有代表性的
 public E set(int index, E e) {
            rangeCheck(index);
            checkForComodification();
            E oldValue = ArrayList.this.elementData(offset + index);
            ArrayList.this.elementData[offset + index] = e;
            return oldValue;
        }
从源代码我们不难看出,其实用的还是修改数组中元素的方法。直接根据索引找到数据进行赋值修改即可!

原本还想讲更多的方法的,但我觉得这些就已经够了,其它的方法要不就是直接,要不就是间接使用了上述的方法,然后在此基础上增加一些逻辑而已。所以就不在往下继续讲了。
为方便大家学习,特别找了一篇实现简单ArrayList的博客
https://www.cnblogs.com/qifengshi/p/6377614.html

在此感谢您的浏览,希望对您有所帮助!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章