解讀ArrayList中的add和remove方法

1. public boolean add(E e)

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

 解讀:

  • 首先確認在數組元素加一後,容量是否能保證。
  • 之後向數組中最後一個元素的下一個位置放置新的元素。

2.public void add(int index, E element)

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    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++;
    }

 解讀:

  • 首先判斷使用者所想插入的位置index是否合法
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);

arraycopy一個本地方法,意味着它底層並非java代碼實現。

參數意義爲

src srcPos dest destPos length
把從原數組src 的srcPos位置開始的length長度的所有元素 複製到dest數組 的destPos位置 想被複制的個數
  • 想要插入的位置的元素及其後面的元素都往後移後。
  • 往索引位置插入element元素。

3.public E remove(int index)//刪除數組中的index位置的對象

根據位置刪

    /**
     * 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;
    }
  • 檢查所要移除的位置是否落在數組元素長度之內。
  • 修改次數+1
  • 把需要刪除的元素賦給oldValue,一遍方法返回舊元素
  • numMoved計算出的是刪除元素後需要移動的元素數。
  • 當numMoved>0 說明刪除元素後需要把後面的元素往前移動。
  • 當numMoved<0 時,說明刪除的元素爲最後一個元素。
  • 直接把最後一個位置置空。
  • 返回被刪值

 

4. public boolean remove(Object o) //刪除數組中的o對象

根據內容刪

    /**
     * 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) {
        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;
    }
  • 因爲對象是否相等需要使用equals方法,但是空對象不能使用equals方法比較。
  • 因此需要先判斷傳入的對象是否爲空。
  • 爲空時  使用==來尋找數組中空對象並刪除。
  • 不爲空時,便使用equals遍歷尋找來刪除相應對象。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章