內容來自於Blog地址,對SparseArray知識進行了收集和整合。
一、SparseArray(稀鬆的數組)
是Android提供的一個工具類,可以更好的優化性能,替代HashMap。實現的思路請查看原Blog的地址。
二、定義一個SparseArray
它和一般的List一樣,可以分配大小,如果不分配自己設置,默認分配10個大小的空間
public SparseArray() {
this(10);
}
public SparseArray(int initialCapacity) {
initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity);
mKeys = new int[initialCapacity];
mValues = new Object[initialCapacity];
mSize = 0;
}
添加一個值
public void put(int key, E value) {}
public void append(int key, E value){}
刪除一個值
public void delete(int key) {}
public void remove(int key) {} //直接調用的delete(int key)
public void removeAt(int index){}
public void clear(){}
修改一個值
public void put(int key, E value)
public void setValueAt(int index, E value)
查找數據
public E get(int key)
public E get(int key, E valueIfKeyNotFound)
折半查找
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;
}