重拾Java之ArrayList源码阅读

    最近换工作了。面试的时候被一个比较老的程序员到地上摩擦,表示很难受。之前因为是从事音视频方面的开发,所以去应聘智能硬件方面的工作。因为都会涉及道JNI层面的开发。所以感觉比较适合。But. 生活真的不是那么的一翻风顺啊,我去面试的时候,面试官问ArrayList和LinkList的区别,暗想这都是老掉牙的问题,果断完美答出。But 他又来句ArrayList具体是怎么实现的?我擦勒,平时只是用的很爽,还真没有仔细看过ArrayList的源码。之后又问道HashMap的原理,我回答说散列,结果又被问怎么散列的。嗯此时我的心里阴影面积很大,被按着地上摩擦......所以决定一看究竟,以免以后被继续摩擦。

下面来看看ArrayList的源码吧。博主查阅的是JDK 1.8中的ArrayList的源码。

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {...}

其中RandomAccess(可随机访问)、Cloneable(可以克隆)、Serializable(可序列化)等3个接口只有声明,里面没有任何变量或者接口方法,可以理解为一个标志作用。 对ArrayList追根查底我们能得到这样一幅结构图:

   

ArrayList中几个重要的全局成员变量:

//默认的ArrayLis的容量值
private static final int DEFAULT_CAPACITY = 10;
//空的对象数组,用于初始化空ArrayList
private static final Object[] EMPTY_ELEMENTDATA = {};
//ArrayList数据储存的地方,transient关键字是反序列化
transient Object[] elementData;
//ArrayList里面元素的个数
private int size;

一、ArrayList的构造方法

public ArrayList() {
        super();
        this.elementData = EMPTY_ELEMENTDATA;
    }

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

public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }


第一个无参构造,数据数组用空数组对象初始化;第二个为有参数的,用集合初始化ArrayList储存数据的数组;第三个自定义初始化容量的ArrayList(后期不够用仞然会变)。

//Arrays.copyOf 方法:
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;
    }

public static native void arraycopy(Object src,  int  srcPos,Object dest, int destPos,int length);  src原数组(被复制的数组)srcPos被复制数组的起始位置;dest目标数组,destPos目标数组的存放复制数据的起始位置;length复制的长度。


二、ArrayList的增删改查以及遍历方法

1.增加数据:add方法

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


private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_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);
    }

private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

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

    可以清晰的看见add方法 首先检查添加的索引位置是否正确,不正确的话直接抛出异常。然后增加一个值,调用ensureCapacityInternal 方法确保ArrayList的容量是足够的(如果不足,则增加ArrayList的容量)。最后调用System.arraycopy 方法把原数组中自index索引位置的元素都向后移动一位,然后给index位置重新复制即可。

    使用ensureCapacityInternal方法,先初步确定最小的容量。然后进一步使用ensureExplicitCapacity方法确定ArrayList的容量;modCount 关键字是记录ArrayList的大小改变的次数;如果容量不够的话,就使用grow方法进行扩增;可以看到grow方法里面做了这样的的事情:newCapacity先为原始容量的1.5倍;如果newCapacity比需要的最小容量小;那么将所需的最小容量赋值给newCapacity;如果newCapacity的值比MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8 值要大(不要纠结MAX_ARRAY_SIZE这个值怎么来的,这是JDK工程师通过大量的实验得出的经验值,我们直接用就好),那么newCapacity的值为hugeCapacity方法的返回值;最后调用Arrays.copyOf方法生新的对象数组赋值给elementData。

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

    到现在为止;add方法的其中一个就被分析完毕了;当然add方法有很多的重载但都大同小异这里就不过多的赘述了。读者可以自己看看。

2.删除数组: remove 方法

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

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
    }

    可以发现remove方法首先是找到那个要删除的元素第一次出现位置,然后调用fastRemove方法将其删除。也就是说如果有重复的元素,只能删除第一个。fastRemove先将index后面的每一个元素都向前面移动一位(这样以来index位置的元素就被index+1这个位置的元素给覆盖了)。最后将原数组中的最后一个元素置为null;相对add方法remove方法比较简单;其他的remove的重载方法也比较简单读者可自己查阅。

3.修改数据 :set方法

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

该方法非常的单纯简单,就是直接把原来的元素值返回;然后直接改变数组中该位置的中的值即可。

4.查询数据:get方法

public E get(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        return (E) elementData[index];
    }

和set方法一样天真无邪。

5.遍历数据:iterator方法

iterator方法比较简单这里不做过多的描述;我们来看看listIterator方法:

public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }

        public boolean hasPrevious() {
            return cursor != 0;
        }

        public int nextIndex() {
            return cursor;
        }

        public int previousIndex() {
            return cursor - 1;
        }

        @SuppressWarnings("unchecked")
        public E previous() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            int i = cursor - 1;
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;
            return (E) elementData[lastRet = i];
        }

        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();

            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        public void add(E e) {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();

            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
                limit++;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }



private class Itr implements Iterator<E> {
        // Android-changed: Add "limit" field to detect end of iteration.
        // The "limit" of this iterator. This is the size of the list at the time the
        // iterator was created. Adding & removing elements will invalidate the iteration
        // anyway (and cause next() to throw) so saving this value will guarantee that the
        // value of hasNext() remains stable and won't flap between true and false when elements
        // are added and removed from the list.
        protected int limit = ArrayList.this.size;

        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor < limit;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            int i = cursor;
            if (i >= limit)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
                limit--;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;

            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

先看看Itr这个类,它实现了Iterator接口:

public interface Iterator<E> {
    //是否含有下一个元素
    boolean hasNext();
    //下一个元素值
    E next(); 
    //移除元素
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }
    //JDK 1.8中新增的方法,先不用管
    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

这个类比较简单,不做分析;看看我们正主listIterator他继承Itr实现了ListIterator 接口

public interface ListIterator<E> extends Iterator<E> {
    //是否有下一个元素值
    boolean hasNext();
    //下一个元素值
    E next();
    //是否含有上一个元素
    boolean hasPrevious();
    //上一个元素值
    E previous();
    //下一个元素的索引
    int nextIndex();
    //上一个元素的索引
    int previousIndex();
    //移除元素
    void remove();
    //设置值
    void set(E e);
    //添加值
    void add(E e);
}

cursor : 下一个要返回元素的下标      lastRet:最后一个返回元素的位置      limit:表示的ArrayList中的元素的个数

previous()方法:当前元素的上一个元素 其索引位置为 cursor-1;如果是第一个元素就没有上一个元素啦;取出值之后将cursor的值赋值为cursor-1;同时也将这个值赋值给lastRet。可以说是ListItr是Itr的升级加强版;它可以添加元素,获取上一个元素等等,这些都是Itr类所办不到的。

6.清空数据:clear方法

public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

其实就是将所有的元素置为null 方便GC回收。


三、JDK 1.8中新增的方法

public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;

            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

forEachRemaining方法是迭代器在JDK 1.8中新增的方法,目前还没看见这个怎么使用,但是这个方法有个新的思想。如果读者有C语言的基础那么一眼就能看明白;这个其实就是函数指针的原型;使用Consumer接口的accept方法对ArrayList中的每个元素进行处理。

public interface Consumer<T> {
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

这样我们只要实现Consumer接口就可以利用accept方法对ArrayList中的每个元素进行自定义的处理。


四、小结

     整体来说ArrayLsit的源码还是比较的善良单纯的。没看过被别人问起来总是心虚,看过之后其实也没什么哈。从看ArrayList的源码,我们可以知道ArrayList做查询的时候或者修改的时候非常的快,但是做插入和删除的时候就不行,尤其是数据量大的时候;原因就是它需要后面的元素都向前移动一位或者向后移动一位;对于这种需要删除和插入较为频繁的我们需要使用LinkedList. 下一节我们来分析下LinkedList的源码:重拾Java之LinkedList源码阅读


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值