sparseArray其实里面维护了两个数组来存储数据
private int[] mKeys;存key通过二分法查找
private Object[] mValues;存value
private int mSize;
//初始化
public SparseArray(int initialCapacity) {
if (initialCapacity == 0) {
mKeys = EmptyArray.INT;
mValues = EmptyArray.OBJECT;
} else {
mValues = ArrayUtils.newUnpaddedObjectArray(initialCapacity);
mKeys = new int[mValues.length];
}
mSize = 0;
}
最主要的方法是put
public void put(int key, E value) {
//查询key的下标获取index
int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
//如果查询到了下标就赋值
if (i >= 0) {
mValues[i] = value;
} else {
//如果查询不到取反再处理
i = ~i;
//如果下标小于size,该位的值为DELETED,就赋值
if (i < mSize && mValues[i] == DELETED) {
mKeys[i] = key;
mValues[i] = value;
return;
}
//如果需要gc&&size>key的长度
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++;
}
}
里面有两个主要方法ContainerHelpers.binarySearch()和gc()
二分法查找下标
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
}
//其实是为了清掉value是DELETED的数据
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);
}
其他好像都没啥