天天看點

Java面試題-請簡單介紹一下ArrayList基本操作?

作者:架構師面試寶典
Java面試題-請簡單介紹一下ArrayList基本操作?

ArrayList是在開發中經常被用到的基于List接口實作的順序存儲容器。其特點就是對資料進行順序的存取,并且可以支援存放null元素,它的底層是采用數組的方式實作存儲。除了沒有實作同步操作之外,其他的操作與Vector的操作是一樣的。下面我們就來分析一下ArrayList的具體實作。

簡單介紹

既然ArrayList底層是采用了數組的方式進行存儲,那麼對于一個數組來講,就有容量和實際大小兩個關鍵參數。如下圖所示。

Java面試題-請簡單介紹一下ArrayList基本操作?

所謂的容量就是指底層數組所能容納資料的多少,而實際大小則是指實際存儲資料的空間的大小。當不斷的往數組中添加資料的時候,容量就會自動增大,也就是後續我們在分析過程中會說到的數組擴容的操作。為了追求效率,ArrayList并沒有Synchroinzed的同步操作,如果需要進行并發的通路就需要自己控制,或者是使用Vector來代替。

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

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;           

上述的兩個參數就可以将上圖中展示的内容做了抽象,其中elementData的大小就是容量,而size的大小就表示了數組實際存儲資料的多少。

構造函數

ArrayList提供了如下的一些構造函數,其中比較關鍵的就是第一個構造函數。在構造函數中會發現,傳入一個初始容量的參數。也就是說在使用ArrayList的時候需要傳入預計需要存儲多少的元素。預設情況下如果不傳入,則會使用DEFAULTCAPACITY_EMPTY_ELEMENTDATA一個空數組來進行初始化。

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

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

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        Object[] a = c.toArray();
        if ((size = a.length) != 0) {
            if (c.getClass() == ArrayList.class) {
                elementData = a;
            } else {
                elementData = Arrays.copyOf(a, size, Object[].class);
            }
        } else {
            // replace with empty array.
            elementData = EMPTY_ELEMENTDATA;
        }
    }           

ArrayList的自動擴容機制

前面我們提到了,當我們不斷的往ArrayList中添加資料的時候,當數組容量裝不下的時候,就會進行自動擴容,而我們也知道往ArrayList中添加資料需要調用一個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;
}

// 進入之後第一步調用的方法
private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
// 計算比較容量比較大小
private static int calculateCapacity(Object[] elementData, int minCapacity) {
      if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
          return Math.max(DEFAULT_CAPACITY, minCapacity);
      }
      return minCapacity;
}

// 根據實際擷取容量進行擴容操作,并且支援 Fast-Fist 機制
private void ensureExplicitCapacity(int minCapacity) {
     modCount++;

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

// 擴容容量增長函數
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);
}

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

如下圖所示,當數組完成擴容之後,會将原來的資料複制到新的數組中,并且新數組後半段内容為空,用來支援後續資料的錄入操作。

Java面試題-請簡單介紹一下ArrayList基本操作?

通過上面的分析我們可以知道,數組擴容操作其實是一個比較耗時、并且比較消耗記憶體的操作,是以在實際使用的過程中,如果我們知道了預先的資料的容量,最好是在構造ArrayList的時候指定容量大小,這樣可以避免因為數組擴容所帶來的資源消耗。

如何擷取元素?

上面我們介紹了如何去往數組中添加一個元素,那麼下面我們就來看看如何從數組中擷取元素,在ArrayList中提供了get()方法來擷取指定位置的資料元素,代碼如下。

/**
 * 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還提供了remove()方法來移除指定位置的元素,或者是指定的元素,并且将移除之後的資料進行傳回,代碼如下。

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

如何修改元素?

ArrayList提供了一個set()方法來修改指定位置的元素操作,代碼如下。

/**
 * Replaces the element at the specified position in this list with
 * the specified element.
 *
 * @param index index of the element to replace
 * @param element element to be stored at the specified position
 * @return the element previously at the specified position
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E set(int index, E element) {
    rangeCheck(index);

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

會看到在這方法中,先将原有位置的元素提取出來,并且直接将原有位置的元素進行了替換,并且傳回了原有位置的元素。

總結

到這裡,對ArrayList資料的增删改查的操作都已經介紹完了。其中比較關鍵的地方就是對于數組的擴容操作。

繼續閱讀