主要方法分析
put方法
/**
*放一個元素到集合
*/
public void put(int key, E value) {
int i = binarySearch(mKeys, 0, mSize, key);
// 返回的大於0 那麼找到有效的值 將原有的值替換掉
// 否則, 如果i < size 那麼 賦值
if (i >= 0) {
mValues[i] = value;
} else {
i = ~i;
// 找到對應地方 賦值 返回
if (i < mSize && mValues[i] == DELETED) {
mKeys[i] = key;
mValues[i] = value;
return;
}
//如果需要Gc 而且 size 大於 長度 那麼進行gc回收
if (mGarbage && mSize >= mKeys.length) {
gc();
// Search again because indices may have changed.
i = ~binarySearch(mKeys, 0, mSize, key);
}
if (mSize >= mKeys.length) {
int n = Math.max(mSize + 1, mKeys.length * 2);
int[] nkeys = new int[n];
Object[] nvalues = new Object[n];
// Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
mKeys = nkeys;
mValues = nvalues;
}
if (mSize - i != 0) {
// Log.e("SparseArray", "move " + (mSize - i));
System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
}
mKeys[i] = key;
mValues[i] = value;
mSize++;
}
}
//binarySearch 二分搜索算法
/**
* 參數 a -> Keys數組
start -> 數組起點
len -> 數組長度
key -> 需要找的key值
返回 查找到的索引
*
*/
private static int binarySearch(int[] a, int start, int len, int key) {
int high = start + len, low = start - 1, guess;
while (high - low > 1) {
guess = (high + low) / 2;
if (a[guess] < key)
low = guess;
else
high = guess;
}
if (high == start + len)
return ~(start + len);
else if (a[high] == key)
return high;
else
return ~high;
}
put方法通過二分法找到對應的檢索,進行數組賦值的過程
-
通過二分查找算法,計算key的索引值.
- 如果索引值大於0,說明有key對應的value存在,直接替換value即可.
- 如果索引值小於0,對索引值取反,獲取key應該插入的座標i.
-
判斷是否需要擴容:1.需要擴容,則先擴容; 2.不需要擴容,則利用System.arraycopy移動相應的元素,進行(key,value)鍵值對插入.
get方法
//get 方法
public E get(int key, E valueIfKeyNotFound) {
int i = binarySearch(mKeys, 0, mSize, key);
if (i < 0 || mValues[i] == DELETED) {
return valueIfKeyNotFound;
} else {
return (E) mValues[i];
}
}
get函數就是利用二分查找獲取key的下標,然後從object[] value數組中根據下標獲取值. SparseArray比HashMap有更好的性能:
- SparseArray更加節約內存,一個int[]數組存儲所有的key,一個object[] 數組存儲所有的value.
- HashMap遇到衝突時,時間複雜度爲O(n).而SparseArray不會有衝突,採用二分搜索算法,時間複雜度爲O(lgn).
總結
名稱 | 名字 | 實現 | 線程安全性 | 查詢複雜度 |
---|---|---|---|---|
SparseArray | 稀疏數組 | 維持兩種表 一個是keys 數組 一個是Values 數組 key -> Value 通過每個值在數組裏面的檢索來關聯 值的查找通過二分法 查找 keys數組值後得到index值後 再去values數組的值 | 不安全 | O(lgn) |
HashMap | 散列鏈表 | 數組鏈表 一個HashMapEntry數組 可以通過key值生成一個index 然後存放到對應的數組和鏈表上面 | 不安全 | 未衝突的情況下是O(1),衝突的情況下是O(n) |