SparseArray 原理分析

本文发表于KuTear’s Blog,转载请注明

Put

//SparseArray.java
public void put(int key, E value) {
       //二分查找,SparseArray是由小到大排序的
       //找到是返回该key对应的index
       //没找到时该key在这时应该放置index的补运算的结果(负数)
        int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
        if (i >= 0) {  //找到
            mValues[i] = value;
        } else { //没找到
            i = ~i;  //求补,得到该放置的位置.
            if (i < mSize && mValues[i] == DELETED) {  //该放置的位置没有数据在还没有元素/1个元素或者有进行删除数据的时候出现
                mKeys[i] = key;
                mValues[i] = value;
                return;
            }
            if (mGarbage && mSize >= mKeys.length) {
                gc(); //数据紧凑
                // 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
//使数据紧凑(数据集中在数组前端)
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.
//[不做参数范围检测]
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;
        }
        //数组容量不够,扩容
        @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减一和做数组紧缩操作,而是在要用的做,
               //比如调getSize()就会做数组紧缩,这样才可以得到真正的size
            }
        }
}

Append

//SparseArray.java
//由于SparseArray几乎所有的操作都是基于二分查找算法,所以append的实现肯定不能
//直接append
public void append(int key, E value) {
        //如果值不够大,当然排不到最后,转为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;
}
    原文作者:KuTear
    原文地址: https://www.jianshu.com/p/6a69200069ae
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞