SparseArray是android里为<Interger,Object>这样的Hashmap而专门写的类,目的是提高效率,其核心是折半查找函数(binarySearch)。
在Android中,当我们需要定义
HashMap<Integer, E> hashMap = new HashMap<Integer, E>();
时,我们可以使用如下的方式来取得更好的性能。
SparseArray<E> sparseArray = new SparseArray<E>();
在SparseArray文件中,在查找的过程中使用了二分查找法,极大的提高了性能
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;
}