ArrayList源码分析

2019-01-24  本文已影响7人  ohjam

ArrayList JDK1.8 概述

ArrayList 数组队列,跟普通的数组相比,数组队列的容量能动态增长。

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

继承:AbstractList
实现:List RandomAccess Cloneable java.io.Serializable
几个重要参数

    private static final int DEFAULT_CAPACITY = 10;
    private static final Object[] EMPTY_ELEMENTDATA = {};
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    transient Object[] elementData;
    private int size;

构造函数

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

无参构造函数,给elementData赋值空数组。

/**
     * Constructs an empty list with the specified initial capacity.
     */
    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);
        }
    }

int入参构造函数,可指定初始化容量。

/**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     */
    public ArrayList(Collection<? extends E> c) {
        // 将Collection转换为数组
        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;
        }
    }

常用函数

add方法

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

get方法

        public E get(int index) {
            // 检查是否数组越界
            rangeCheck(index);
            // 判断是否有其他对象对此List进行了元素的操作
            checkForComodification();
            // 取出元素
            return ArrayList.this.elementData(offset + index);
        }

remove方法 (入参为int)

    /**
     * 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);
        // 修改计数增1
        modCount++;
        // 取出将要删除的值
        E oldValue = elementData(index);
        
        int numMoved = size - index - 1;
        if (numMoved > 0)
            // 通过System.arraycopy把所要删除的元素后面的元素拷贝到所要删除的元素位置
            // 相当于覆盖掉所要删除的元素
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        // 第size位置为null后size的值-1
        elementData[--size] = null; // clear to let GC do its work
        // 返回删除的元素
        return oldValue;
    }

remove方法 (入参为Object)

    /**
     * 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&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;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) {
        // 先判断入参是否为null
        // 遍历数组并对比每个元素与入参是否相等
        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;
    }

fastRemove方法

    /*
     * 不检查是否数组越界,不返回要删除的元素的快速删除
     * 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
    }
上一篇下一篇

猜你喜欢

热点阅读