ArrayList源码分析-面试必会

今天来说一说JAVA中我们比较熟悉的 ArrayList ,据说在面试中要你手写ArrayList都是有可能的,所以我i这两天读了ArrayList的源码,参考了一些资料,来把我的理解分享一下。

ArrayList 的特点

  1. ArrayList底层是基于Object[] 数组来实现的, 是一个动态扩展数组 ,Object数组默认容量是10,当长度不够时会自动将容量扩展到其原来的1.5倍。自动增长会带来数据向新数组的拷贝。

  2. ArrayList插入删除操作都是通过数据在数组中的移动实现的,所以增删效率底,而改查怎依然是通过数组下标直接定位,改查效率高

  3. ArrayList线程不同步,也就是线程不安全

  4. ArayList是有序的,元素可重复的,允许元素为null

  5. ArrayList实现了Serializable接口,因此它支持序列化,能够通过序列化传输,实现了RandomAccess接口,支持快速随机访问,实际上就是通过下标序号进行快速访问,实现了Cloneable接口,能被克隆

源码分析

下面进行源码分析,我知道有些小白看到源码就会有惧怕感,但没关系,在我逐一讲解的同时请你打开你的IDE进入到ArrayList的源码跟我一起看,你一定会感觉好多了。

一.属性分析

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * Default initial capacity.
     * 默认初始化容量为10
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     * 如果自定义容量为0,则会默认用他俩初始化ArrayList,或者用于空数组替换
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 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.
     * 如果没有定义容量则会用他来初始化ArrayList,或者用于空数组对比
     */
    private static final Object[] DEFAULTCAPACITY_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 == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     *  这就是底层用到的数组,非私有,以简化嵌套类访问
     *  transient 在已经实现序列化的类中不允许某变量序列化
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     * 实际ArrayList集合的大小
     * @serial
     */
    private int size;

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

二.构造方法分析

用无参构造初始化,默认容量为10

public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

构造一个初始容量为initialCapacity的空列表

如果传入的initialCapacity为负数则会抛IllegalArgumentException异常

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

通过结合做参数的形式初始化

按照集合的迭代返回他们的顺序,C集合的元素将被放入列表

如果集合为空则初始化为空数组

public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

三.主方法解析

trimToSize()

用来最小化实例存储,将容器大小调整为当前元素所占用的容量大小,再底层的Copy方法实现了新数组的拷贝

/**
 * Trims the capacity of this <tt>ArrayList</tt> instance to be the
 * list's current size.  An application can use this operation to minimize
 * the storage of an <tt>ArrayList</tt> instance.
 */
public void trimToSize() {
    modCount++;
    if (size < elementData.length) {
        elementData = (size == 0)
          ? EMPTY_ELEMENTDATA
          : Arrays.copyOf(elementData, size);
    }
}
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) {
    @SuppressWarnings("unchecked")
    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 Object newInstance(Class<?> componentType, int length)
    throws NegativeArraySizeException {
    return newArray(componentType, length);
}
clone()

克隆出一个新数组,通过调用Objectclone()方法来得到一个新的ArrayList对象,然后将elementData复制给该对象并返回。

/**
     * Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The
     * elements themselves are not copied.)
     *
     * @return a clone of this <tt>ArrayList</tt> instance
     */
    public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }
add(E e)

再数组添加元素

数据尾部插入,由于不会影响其他元素,因此会直接插入到后面。

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

看到它首先调用了ensureCapacityInternal()方法.注意参数是size+1,这是个面试考点。

该方法做了两件事:计算容量+确保容量

if语句进行计算容量,如果elementData是空,则返回默认容量10和size+1的最大值,否则返回size+1

private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}

计算完容量后,进行确保容量可用:(modCount不用理它,它用来计算修改次数)

如果size+1 > elementData.length证明数组已经放满,则增加容量,调用grow()

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

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

增加容量:默认1.5倍扩容。

  1. 获取当前数组长度=>oldCapacity

  2. oldCapacity>>1 表示将oldCapacity右移一位(位运算),相当于除2。再加上1,相当于新容量扩容1.5倍。

  3. 如果newCapacity>1=1,1<2所以如果不处理该情况,扩容将不能正确完成。

  4. 如果新容量比最大值还要大,则将新容量赋值为VM要求最大值。

  5. 将elementData拷贝到一个新的容量中。

    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(int index, E element)

1.当添加数据是在首位插入时,先将新的数据放入到新的数组内,然后将原始数组中的数据复制到新的数组。
2.当数据插入的位置是中间位置时,先将插入位置前面的数据先放到新的数组里,再放新的数据,再复制旧的数据完成添加。

3.数据尾部插入,由于不会影响其他元素,因此会直接插入到后面。

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

rangeCheckForAdd()是越界异常检测方法。ensureCapacityInternal()之前有讲,着重说一下System.arrayCopy方法:

private void rangeCheckForAdd(int index) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);
set(int index,E element)

覆盖旧值并返回。

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

异常检查

private void rangeCheck(int index) {
    if (index < 0 || index >= this.size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void checkForComodification() {
    if (ArrayList.this.modCount != this.modCount)
        throw new ConcurrentModificationException();
}

获取原值

E elementData(int index) {
        return (E) elementData[index];
    }

覆盖

ArrayList.this.elementData[offset + index] = e;
indexOf(Object o)

比较简单 ,根据Object对象获取数组中的索引值。

如果o为空,则返回数组中第一个为空的索引;不为空也类似。

注意:通过源码可以看到,该方法是允许传空值进来的。

public int indexOf(Object o) {
    if (o == null) {
        for (int i = 0; i < size; i++)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}
get(int index)

返回指定下标处的元素的值。

rangeCheck(index)会检测index值是否合法,如果合法则返回索引对应的值。

public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}
remove(int index)

删除指定下标的元素。

1.从头部删除,删除头结点然后移动后面的数据,最后一个元素置空。
2.从中间指定位置删除,找到要删除数据的位置,删除后,后面的数据移动,最后一个元素置空。

3.从尾部删除:直接删除尾部数据完成删除操作。

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

这么看下来其实ArrayList还不难,而且也是比较基础的东西,好好钻研吧,加油!

我的博客:http://www.troubleq.com

https://segmentfault.com/u/troubleq

作者参考:源码 + JAVA知音

网址:www.javazhiyin.com

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值