JDK源碼閱讀ArrayList

#ArrayList的具體實現java

ArrayList是List接口的具體實現,是在實際生產環境中用的很是多的一種工具類算法

##數據結構數組

  1. 顧名思義,從ArrayList的名字中咱們就能夠看出,ArrayList是基於數組的一種實現.
private transient Object[] elementData; //對象存儲
private int size; //實際含有對象的大小  size <= elementData.length

##主要代碼實現數據結構

構造函數

// 構造函數比較簡單, 初始化對象數組就能夠了
	public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity]; 
    }

add

//將對象添加到數組的末尾便可
	public boolean add(E e) {
        ensureCapacityInternal(size + 1);  //對List進行擴容
        elementData[size++] = e;
        return true;
    }
	//在index位置添加新的數據, >=index的則所有後移一位
	public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // 擴容
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index); // 後移
        elementData[index] = element;
        size++;
    }
	
	//擴容實現
	private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1); // 計算擴容後的數組大小 JDK > 1.7的算法, 與1.7之前的算法不一樣
        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);
    }

set

//替換index的原有數據
	public E set(int index, E element) {
        rangeCheck(index);

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

get

//直接取值, 數組結構的最大優點
	E elementData(int index) {
        return (E) elementData[index];
    }

remove

//根據index remove
	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;
    }
	//根據Object  remove
	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;
    }

其他函數基本與這幾個相似

迭代器, TODO:暫時還沒看太明白,改天繼續分析

相關文章
相關標籤/搜索