Volley ByteArrayPool

来源:互联网 发布:空军 知乎 编辑:程序博客网 时间:2024/06/06 15:42
 private List<byte[]> mBuffersByLastUse = new LinkedList<byte[]>(); //维护一个优先队列,在容量超过mSizeLimit时候从优先队列的队头开始删除    private List<byte[]> mBuffersBySize = new ArrayList<byte[]>(64);    //用来存放所有的数组,因为是按照二分查找插入的所以是有序的。
//这个返回buff的程序不知道为什么不用二分查找public synchronized byte[] getBuf(int len) {        for (int i = 0; i < mBuffersBySize.size(); i++) {            byte[] buf = mBuffersBySize.get(i);            if (buf.length >= len) {                mCurrentSize -= buf.length;                mBuffersBySize.remove(i);                mBuffersByLastUse.remove(buf);                return buf;            }        }        return new byte[len];    }
  public synchronized void returnBuf(byte[] buf) {        if (buf == null || buf.length > mSizeLimit) {            return;        }        mBuffersByLastUse.add(buf);        int pos = Collections.binarySearch(mBuffersBySize, buf, BUF_COMPARATOR);        //如果找不到则pos=-(low+1)即返回的是应该的插入位置的相反数,找到了那么pos也是插入相同元素的位置。        if (pos < 0) {            pos = -pos - 1;        }        mBuffersBySize.add(pos, buf);        mCurrentSize += buf.length;        trim();    }
//二分查找 private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {        int low = 0;        int high = l.size()-1;        while (low <= high) {            int mid = (low + high) >>> 1;            T midVal = l.get(mid);            int cmp = c.compare(midVal, key);            if (cmp < 0)                low = mid + 1;            else if (cmp > 0)                high = mid - 1;            else                return mid; // key found        }        return -(low + 1);  // key not found    }

看懂二分查找了

当low==high时,要找的值要么在左边,要么在右边,在左边的时候下一步high=low-1; 此时low指向的值刚好比key大一点,在右边的时候low=high+1,此时low也是比key大一点。上面那个函数return -(low + 1);是为了避开0这种情况。

0 0
原创粉丝点击