/**
* Creates a new SparseArray containing no mappings.
*/
public SparseArray() {
this(10);
}
/**
* Creates a new SparseArray containing no mappings that will not
* require any additional memory allocation to store the specified
* number of mappings. If you supply an initial capacity of 0, the
* sparse array will be initialized with a light-weight representation
* not requiring any additional array allocations.
*/
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;
}
构造方法很简单,就两个构造方法,默认的不传capacity参数的情况下创建的数组长度是10。
常规操作
添加数据
/**
* Adds a mapping from the specified key to the specified value,
* replacing the previous mapping from the specified key if there
* was one.
*/publicvoidput(int key, E value){
//通过二分查找来找到mKeys数组中对应key的index索引。int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
if (i >= 0) { //如果找到了,表示之前存过这个key,则覆盖旧的value。
mValues[i] = value;
} else {
i = ~i;//取反,把负数变成正数。(注释一)if (i < mSize && mValues[i] == DELETED) {//如果这个key对应的value之前被删除了,但是还没有被执行gc操作,目前还是DELETED状态,那么就复用此index。(注释二)
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);//插入新key,如果需要扩容,就像ArrayList那样,通过copy操作来完成。
mValues = GrowingArrayUtils.insert(mValues, mSize, i, value);//插入新value
mSize++;//表示新添加了一对key-value键值对。
}
}
staticintbinarySearch(int[] array, int size, int value){
int lo = 0;
int hi = size - 1;
while (lo <= hi) {
finalint mid = (lo + hi) >>> 1;
finalint midVal = array[mid];
if (midVal < value) {
lo = mid + 1;
} elseif (midVal > value) {
hi = mid - 1;
} else {
return mid; // value found
}
}
return ~lo; // value not present
}
/**
* Removes the mapping at the specified index.
*
* <p>For indices outside of the range <code>0...size()-1</code>,
* the behavior is undefined.</p>
* 主要index的范围问题
*/publicvoidremoveAt(int index){
if (mValues[index] != DELETED) {
mValues[index] = DELETED;
mGarbage = true;
}
}
get操作
public E get(int key){
return get(key, null);
}
/**
* Gets the Object mapped from the specified key, or the specified Object
* if no such mapping has been made.
*/@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
privatevoidgc(){
// 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);
}