ArrayLIst(JDK1.8)

一.ArrayList 實現的接口

 

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

ArrayList 是一個動態數組,能夠自動擴容,在添加的時候首先判斷是不是需要擴容

 private void ensureExplicitCapacity(int minCapacity) {//minCapacity=size+1
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);//這就是擴容方法
    }


​​二.類屬性

private static final int DEFAULT_CAPACITY = 10  默認容量
private static final Object[] EMPTY_ELEMENTDATA = {};空對象
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};默認空對象
Object[] elementData;對象數組,數據存儲
int size;數組存放數據長度

三.方法

1.add()

 public boolean add(E e) {//添加數據到數組末尾
        ensureCapacityInternal(size + 1);  // Increments modCount!!
                    //判斷是不是需要擴容,如果是就自動擴容
        elementData[size++] = e;
        return true;
    }

2.add(O,index)

public void add(int index, E element) {//添加到指定位置
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);//直接用arraycopy複製
        elementData[index] = element;
        size++;
    }

3.set(int index, E element) 

返回值爲修改前的數據

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

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

4. remove(int index)

返回移除的數據

 

 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
        //size-1

        return oldValue;
    }
5.clear()
  for循環置空,效率很慢

6.contains/indexOf

全都是用for遍歷數組,很慢,儘量少用

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章