欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

集合之ArrayList

程序员文章站 2022-05-28 16:54:05
...
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * 默认容量为10
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 空的数组
     */
    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.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 用于存储数据的数组,创建ArrayList的时候被初始化
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     *元素的数量(不是elementData的长度)
     */
    private int size;

    /**
     *指定容量的构造方法
     ** 	如果确定列表长度,可以使用此方法来创建列表,省去了扩容的消耗
     ** 	长度小于10的情况,也可以使用此方法来创建列表 节省空间	
     */
    public ArrayList(int initialCapacity) {
    	/**
    	 * initialCapacity大于0时,创建initialCapacity长度的数组
    	 */
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        }
        //initialCapacity为0时,就使用空数组EMPTY_ELEMENTDATA
        else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        }
        //initialCapacity小于0时抛出异常
        else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * 默认构造器:创建一个空数组
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 初始化一个ArrayList,包含c集合的所有元素
     */
    public ArrayList(Collection<? extends E> c) {
    	//调用Collection的toArray返回一个数组
        elementData = c.toArray();
        
        if ((size = elementData.length) != 0) {
        	//toArray返回的可能不是Object[]类型
        	/**以下情况返回的是String类型
        	 * String[] ss = new String[10];
		 	 * List l = Arrays.asList(ss);
		 	 * System.out.println(l.toArray());
        	 */
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // 如果size为0,elementData为空数组
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     * 清除elementData中空余的空间(elementData的长度可能大于size)
     */
    public void trimToSize() {
        modCount++;
        /**
         * 如果size小于elementData的长度,就清除空闲空间
         */
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
            //重新生成一个size长度的数组,并将elementData中的元素拷贝进来
              : Arrays.copyOf(elementData, size);
        }
    }

    /**
     * 确保容量大小(共外部调用)
     */
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            /**
             * 如果elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA说明最小容量为minCapacity
             */
            ? 0
            /**
             * 如果elementData= DEFAULTCAPACITY_EMPTY_ELEMENTDATA需要扩展,默认初始化长度为10
             */
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    /**
     * 确保容量大小(内部调用)
     */
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        	//最小容量为DEFAULT_CAPACITY 10
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

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

        // minCapacity大于elementData.length就扩展
        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) {
        // 获得当前数组长度
        int oldCapacity = elementData.length;
        //新的数组长度=当前数组长度+0.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //如果新的数组长度小于最小容量minCapacity,则新的数组长度为minCapacity
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        /**
         * 新的数组长度大于MAX_ARRAY_SIZE(Integer.MAX_VALUE - 8),调用hugeCapacity
         * 	要么抛出OOM,要么扩展到Integer.MAX_VALUE长度
         */
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        //创建一个newCapacity长度的新数组,拷贝之前的数据
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
    	/**
    	 * 如果当前数组长度已经达到Integer.MAX_VALUE,此时再继续添加数据就会得到负值
    	 * 	Integer.MAX_VALUE+1 <0
    	 */
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE ://最多扩展到Integer.MAX_VALUE长度
            MAX_ARRAY_SIZE;
    }

    /**
     *返回当前列表内元素的个数
     */
    public int size() {
        return size;
    }

    /**
     * 返回当前列表内是否有元素
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 判断o是否在列表里
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    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;
    }

    /**
     * 返回o在列表中的位置
     */
    public int lastIndexOf(Object o) {
    	/**
    	 * o为null时,遍历数组(最大长度为size)通过==来判断
    	 */
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
        	/**
        	 * o不为null时,遍历数组(最大长度为size)通过equals来判断
        	 * 	如果某个对象重写equals方法,两个不同的对象可能相等
        	 */
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    /**
     * 拷贝一份列表,只是拷贝了元素的引用
     */
    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);
        }
    }


    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // a的长度小于列表元素个数时,就只创建一个size长度的新数组
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;//将第size值设为null
        return a;
    }

    // Positional Access Operations

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

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

        return elementData(index);
    }

    public E set(int index, E element) {
        rangeCheck(index);

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

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

    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //将从index开始的元素都往后移一位
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

    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);
        //列表最后一个元素设为null(不是数组最后一位设为null)
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

    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
    }

    /**
     * Removes all of the elements from this list.  The list will
     * be empty after this call returns.
     */
    public void clear() {
        modCount++;

        //只是将元素全部置为null,elementData数组长度没变
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

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

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

    /**
     * 实现原理:将toIndex之后的元素往前移动到fromIndex之后
     */
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

    /**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * A version of rangeCheck used by add and addAll.
     */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * Constructs an IndexOutOfBoundsException detail message.
     * Of the many possible refactorings of the error handling code,
     * this "outlining" performs best with both server and client VMs.
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    /**
     * Removes from this list all of its elements that are contained in the
     * specified collection.
     *
     * @param c collection containing elements to be removed from this list
     * @return {@code true} if this list changed as a result of the call
     * @throws ClassCastException if the class of an element of this list
     *         is incompatible with the specified collection
     * (<a href="Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if this list contains a null element and the
     *         specified collection does not permit null elements
     * (<a href="Collection.html#optional-restrictions">optional</a>),
     *         or if the specified collection is null
     * @see Collection#contains(Object)
     */
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    
    /**
     * 保留c中的元素,其他的元素都删除
     * @param c
     * @return
     */
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    /**
     * 批量删除
     * @param c
     * @param complement true表示删除c以外的元素 false表示删除c中所含的元素
     * @return
     */
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }
}

 

相关的面试题:

     

1、ArrayList的大小是如何自动增加的?你能分享一下你的代码吗?

    arrayList每次新增元素的时候回确保容量是否够用,如果不够用会扩大容量,重新创建一个更大容量的数组,并将原有元素拷贝进去,具体代码如下

    private void grow(int minCapacity) {
        // 获得当前数组长度
        int oldCapacity = elementData.length;
        //新的数组长度=当前数组长度+0.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //如果新的数组长度小于最小容量minCapacity,则新的数组长度为minCapacity
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        /**
         * 新的数组长度大于MAX_ARRAY_SIZE(Integer.MAX_VALUE - 8),调用hugeCapacity
         * 	要么抛出OOM,要么扩展到Integer.MAX_VALUE长度
         */
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        //创建一个newCapacity长度的新数组,拷贝之前的数据
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

 

2、什么情况下你会使用ArrayList?什么时候你会选择LinkedList?

这又是一个大多数面试者都会困惑的问题。多数情况下,当你遇到访问元素比插入或者是删除元素更加频繁的时候,你应该使用ArrayList。另外一方面,当你在某个特别的索引中,插入或者是删除元素更加频繁,或者你压根就不需要访问元素的时候,你会选择LinkedList。这里的主要原因是,在ArrayList中访问元素的最糟糕的时间复杂度是”1″,而在LinkedList中可能就是”n”了。在ArrayList中增加或者删除某个元素,通常会调用System.arraycopy方法,这是一种极为消耗资源的操作,因此,在频繁的插入或者是删除元素的情况下,LinkedList的性能会更加好一点。

3、当传递ArrayList到某个方法中,或者某个方法返回ArrayList,什么时候要考虑安全隐患?如何修复安全违规这个问题呢?

当array被当做参数传递到某个方法中,如果array在没有被复制的情况下直接被分配给了成员变量,那么就可能发生这种情况,即当原始的数组被调用的方法改变的时候,传递到这个方法中的数组也会改变。下面的这段代码展示的就是安全违规以及如何修复这个问题。

ArrayList被直接赋给成员变量——安全隐患:

集合之ArrayList
            
    
    博客分类: Jdk源码阅读 集合ArrayList 

修复这个安全隐患:

集合之ArrayList
            
    
    博客分类: Jdk源码阅读 集合ArrayList 

4、如何复制某个ArrayList到另一个ArrayList中去?写出你的代码?

下面就是把某个ArrayList复制到另一个ArrayList中去的几种技术:

  1. 使用clone()方法,比如ArrayList newArray = oldArray.clone();
  2. 使用ArrayList构造方法,比如:ArrayList myObject = new ArrayList(myTempObject);
  3. 使用Collection的copy方法。

注意1和2是浅拷贝(shallow copy)。

5、在索引中ArrayList的增加或者删除某个对象的运行过程?效率很低吗?解释一下为什么?

在ArrayList中增加或者是删除元素,要调用System.arraycopy这种效率很低的操作,如果遇到了需要频繁插入或者是删除的时候,你可以选择其他的Java集合,比如LinkedList。看一下下面的代码:

在ArrayList的某个索引i处添加元素:

    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //将从index开始的元素都往后移一位
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

 删除ArrayList的某个索引i处的元素:

    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);
        //列表最后一个元素设为null(不是数组最后一位设为null)
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

 

相关标签: 集合 ArrayList