Android源码中遇到的Utils

Author Avatar
MoonChen 3月 17, 2017

总结一下翻阅Android源码中碰到有意思的Utils类。

SparseArray:ContainerHelpers

ContainerHelpers提供了二分查找的方法。

static int binarySearch(int[] array, int size, int value) {
        int lo = 0;
        int hi = size - 1;

        while (lo <= hi) {
            final int mid = (lo + hi) >>> 1;
            final int midVal = array[mid];

            if (midVal < value) {
                lo = mid + 1;
            } else if (midVal > value) {
                hi = mid - 1;
            } else {
                return mid;  // value found
            }
        }
        return ~lo;  // value not present
    }