【转】SparseArray

SparseArray是android里为<Interger,Object>这样的Hashmap而专门写的class,目的是提高效率,其核心是折半查找函数(binarySearch),今天在看这个class的实现时发现一个很好的设计: 

    public void remove(int key) {
        delete(key);
    }
remore和delete都实现了,功能当然是一样的,对用户来说,想用delete,和remove的都可以。
起折半查找算法也写的非常棒:
    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;
    }

你可能感兴趣的:(array)