SparseArray 原理分析

本文發(fā)表于KuTear's Blog,轉(zhuǎn)載請注明

Put

//SparseArray.java
public void put(int key, E value) {
       //二分查找,SparseArray是由小到大排序的
       //找到是返回該key對應(yīng)的index
       //沒找到時該key在這時應(yīng)該放置index的補運算的結(jié)果(負數(shù))
        int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
        if (i >= 0) {  //找到
            mValues[i] = value;
        } else { //沒找到
            i = ~i;  //求補,得到該放置的位置.
            if (i < mSize && mValues[i] == DELETED) {  //該放置的位置沒有數(shù)據(jù)在還沒有元素/1個元素或者有進行刪除數(shù)據(jù)的時候出現(xiàn)
                mKeys[i] = key;
                mValues[i] = value;
                return;
            }
            if (mGarbage && mSize >= mKeys.length) {
                gc(); //數(shù)據(jù)緊湊
                // Search again because indices may have changed.
                i = ~ContainerHelpers.binarySearch(mKeys, mSize, key);
            }
            mKeys = GrowingArrayUtils.insert(mKeys, mSize, i, key);
            mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);
            mSize++;
        }
}
//SparseArray.java
//使數(shù)據(jù)緊湊(數(shù)據(jù)集中在數(shù)組前端)
private void gc() {
        // Log.e("SparseArray", "gc start with " + mSize);
        int n = mSize;
        int o = 0;
        int[] keys = mKeys;
        Object[] values = mValues;
        for (int i = 0; i < n; i++) {
            Object val = values[i];
            if (val != DELETED) {
                if (i != o) {
                    keys[o] = keys[i];
                    values[o] = val;
                    values[i] = null;
                }

                o++;
            }
        }
        mGarbage = false;
        mSize = o;
        // Log.e("SparseArray", "gc end with " + mSize);
}
//ContainerHelpers.java
// This is Arrays.binarySearch(), but doesn't do any argument validation.
//[不做參數(shù)范圍檢測]
static int binarySearch(int[] array, int size, int value) {
        int lo = 0;
        int hi = size - 1;
        while (lo <= hi) {
            final int mid = (lo + hi) >>> 1;
            final int midVal = array[mid];
            if (midVal < value) {
                lo = mid + 1;
            } else if (midVal > value) {
                hi = mid - 1;
            } else {
                return mid;  // value found
            }
        }
        return ~lo;  // value not present
}
//GrowingArrayUtils.java
public static <T> T[] insert(T[] array, int currentSize, int index, T element) {
        assert currentSize <= array.length;
        if (currentSize + 1 <= array.length) {
            //(T[] src, int srcPos, T[] dst, int dstPos, int length)
            //也就是把array的index(包括自身)后的元素往后移動1個單位
            System.arraycopy(array, index, array, index + 1, currentSize - index);
            array[index] = element;
            return array;
        }
        //數(shù)組容量不夠,擴容
        @SuppressWarnings("unchecked")
        T[] newArray = ArrayUtils.newUnpaddedArray((Class<T>)array.getClass().getComponentType(),
                growSize(currentSize));
        //growSize(currentSize) ==> return currentSize <= 4 ? 8 : currentSize * 2;
        System.arraycopy(array, 0, newArray, 0, index);
        newArray[index] = element;
        System.arraycopy(array, index, newArray, index + 1, array.length - index);
        return newArray;
}

Delete & Remove

//SparseArray.java
public void remove(int key) {
        delete(key);
}

public void delete(int key) {
        int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
        if (i >= 0) {
            if (mValues[i] != DELETED) {
                mValues[i] = DELETED;
                mGarbage = true;
                //在這里并沒有把mSize減一和做數(shù)組緊縮操作,而是在要用的做,
               //比如調(diào)getSize()就會做數(shù)組緊縮,這樣才可以得到真正的size
            }
        }
}

Append

//SparseArray.java
//由于SparseArray幾乎所有的操作都是基于二分查找算法,所以append的實現(xiàn)肯定不能
//直接append
public void append(int key, E value) {
        //如果值不夠大,當然排不到最后,轉(zhuǎn)為put
        if (mSize != 0 && key <= mKeys[mSize - 1]) {
            put(key, value);
            return;
        }
        if (mGarbage && mSize >= mKeys.length) {
            gc();
        }
        mKeys = GrowingArrayUtils.append(mKeys, mSize, key);
        mValues = GrowingArrayUtils.append(mValues, mSize, value);
        mSize++;
}
//GrowingArrayUtils.java
public static <T> T[] append(T[] array, int currentSize, T element) {
        assert currentSize <= array.length;
        //申請新容量
        if (currentSize + 1 > array.length) {
            @SuppressWarnings("unchecked")
            T[] newArray = ArrayUtils.newUnpaddedArray(
                    (Class<T>) array.getClass().getComponentType(), growSize(currentSize));
            System.arraycopy(array, 0, newArray, 0, currentSize);
            array = newArray;
        }
        array[currentSize] = element;
        return array;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容