美文网首页
Android-SparseArray源码解析

Android-SparseArray源码解析

作者: zzq_nene | 来源:发表于2021-01-19 10:44 被阅读0次

一、SparseArray原理

SparseArray中采用的是双数组的方式,在SparseArray有一个int数组和一个Object数组,SparseArray在remove的时候,也不会将内存回收,而是对remove的index位置对应的Object数组的数据设置为DELETED,DELETED也是一个Object对象,这样做的目的是为了复用,因为SparseArray插入数据会根据传入的index进行插入,可能会在数组的中间插入,而如果有可以复用的,那么就不需要复制拷贝的操作,直接复用就可以了,这样就省去了对数据复制拷贝移动的操作,节约了性能的消耗。
SparseArray在增删查询的时候,对应的key所在的索引位置,均是采用的二分查找的方式进行。

二、SparseArray#put

1.SparseArray#put

    public void put(int key, E value) {
        // 通过二分查找查询对应的key在mKeys数组中的位置
        int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
        // 如果i大于0,说明mKeys中有该key,则直接替换value
        if (i >= 0) {
            mValues[i] = value;
        } else {
            // 如果mKeys中没有该key,则返回的是最接近且key的一个非运算值
            // 将该值再一次取非
            i = ~i;
            // 判断该key是否满足条件,并且是否是之前被remove的,如果是,则进行复用
            if (i < mSize && mValues[i] == DELETED) {
                mKeys[i] = key;
                mValues[i] = value;
                return;
            }
            // 如果mSize大于mKeys数组长度,并且mGarbage为true,进行gc回收
            // mGarbage是在remove操作之后才置为true的,但是为true并不会立马gc进行回收
            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++;
        }
    }

2.ContainerHelpers#binarySearch

    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
    }

3.GrowingArrayUtils#insert

    public static <T> T[] insert(T[] array, int currentSize, int index, T element) {
        // 在put的时候currentSize就是传入的mSize
        assert currentSize <= array.length;
        // 如果currentSize+1之后还是小于等于array数组的长度
        // 说明不需要扩容,可以直接将数据添加进入
        // 但是在添加的时候需要进行数据的复制拷贝移动操作,将插入到当前位置后续的数据向后移动一位
        if (currentSize + 1 <= array.length) {
            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));
        // 将index位置前面的数据都从旧的数组中拷贝到新的数组中,拷贝index位置前面的index个数据
        System.arraycopy(array, 0, newArray, 0, index);
        // 对index位置进行赋值
        newArray[index] = element;
        // 将旧的数组中的index位置开始向后的数据都拷贝到新的数组中
        // 拷贝个数就是旧的数组长度减去index
        System.arraycopy(array, index, newArray, index + 1, array.length - index);
        return newArray;
    }
    // 数组扩容时,新的数组长度计算,是在当前长度的基础上进行翻倍
    public static int growSize(int currentSize) {
        return currentSize <= 4 ? 8 : currentSize * 2;
    }

三、SparseArray的删除操作

remove操作其实就是将对应位置上的value置为DELETED,并且将mGarbage设置为true

    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;
            }
        }
    }
    public void removeAt(int index) {
        if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) {
            // The array might be slightly bigger than mSize, in which case, indexing won't fail.
            // Check if exception should be thrown outside of the critical path.
            throw new ArrayIndexOutOfBoundsException(index);
        }
        if (mValues[index] != DELETED) {
            mValues[index] = DELETED;
            mGarbage = true;
        }
    }
    public void removeAtRange(int index, int size) {
        final int end = Math.min(mSize, index + size);
        for (int i = index; i < end; i++) {
            removeAt(i);
        }
    }

四、SparseArray的get操作

SparseArray的get操作,其实也是通过二分查找查询到key在对应的mKeys中的索引位置,然后找得到对应的value,如果value对应的是DELETED或者索引位置小于0,则说明查询不到对应的数据,返回一个null或者自定义的一个返回值

    public E get(int key) {
        return get(key, null);
    }

    @SuppressWarnings("unchecked")
    public E get(int key, E valueIfKeyNotFound) {
        int i = ContainerHelpers.binarySearch(mKeys, mSize, key);

        if (i < 0 || mValues[i] == DELETED) {
            return valueIfKeyNotFound;
        } else {
            return (E) mValues[i];
        }
    }

五、gc回收操作

    private void gc() {
        // Log.e("SparseArray", "gc start with " + mSize);

        int n = mSize;
        int o = 0;
        int[] keys = mKeys;
        Object[] values = mValues;
        // 这里的gc回收操作,其实就是回收index位置上value为DELETED的,将之置为null
        // 并且将后续的数据全部前移一位
        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);
    }

相关文章

网友评论

      本文标题:Android-SparseArray源码解析

      本文链接:https://www.haomeiwen.com/subject/ulciqktx.html