内容来自于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;
}