用Java写一个简单的Bitmap

/**
 * Bitmap用于标识[low, high]区间内的数的占用情况,
 * 进一步可以用来去重,用来排序等
 */
private static class Bitmap {
    // 区间的左边界,默认为0
    private int low;
    // 区间的右边界
    private int high;

    // bitmap
    private byte[] bitmap;

    public Bitmap(int high) {
        this(0, high);
    }

    public Bitmap(int low, int high) {
        this.low = low;
        this.high = high;
        bitmap = new byte[(high - low) / Byte.SIZE + 1];
    }

    /**
     * 将x加入到bitmap中
     *
     * @param x 将要加入bitmap的数字
     * @return 如果x不在[low, high]区间中,返回false,如果将x加入bitmap成功则返回true
     */
    public boolean add(int x) {
        if (x < low || x > high) return false;
        int bitIndex = x - low;
        int blockIndex = bitIndex / Byte.SIZE;
        int offset = bitIndex % Byte.SIZE;
        byte mask = (byte) (Byte.MIN_VALUE >>> offset);
        bitmap[blockIndex] |= mask;
        return true;
    }

    /**
     * 将x从bitmap中删除
     *
     * @param x 将要从bitmap中删除的数字
     * @return 如果x不在[low, high]区间中,返回false,如果将x从bitmap删除成功则返回true
     */
    public boolean remove(int x) {
        if (x < low || x > high) return false;
        int bitIndex = x - low;
        int blockIndex = bitIndex / Byte.SIZE;
        int offset = bitIndex % Byte.SIZE;
        byte mask = (byte) (Byte.MIN_VALUE >>> offset);
        bitmap[blockIndex] &= ~mask;
        return true;
    }

    /**
     * 判断bitmap中是否存在数字x
     *
     * @param x
     * @return 如果x不在[low, high]区间中或者bitmap中不存在x,返回false,如果bitmap中存在x则返回true
     */
    public boolean contains(int x) {
        if (x < low || x > high) return false;
        int bitIndex = x - low;
        int blockIndex = bitIndex / Byte.SIZE;
        int offset = bitIndex % Byte.SIZE;
        byte mask = (byte) (Byte.MIN_VALUE >>> offset);
        return (bitmap[blockIndex] & mask) != 0;
    }

    public int getLow() {
        return low;
    }

    public int getHigh() {
        return high;
    }

}
posted @ 2020-07-14 21:41  SanjiApollo  阅读(368)  评论(0编辑  收藏  举报