實現簡單的BitMap

LZC發表於2021-06-29
public class BitMap {
    private int[] values;
    public BitMap() {
        this.values = new int[1];
    }

    public void setBit(int n, boolean value) {
        int index = n / Integer.SIZE;
        int offset = n % Integer.SIZE;
        if (index >= values.length) {
            // 新陣列長度為原來的兩倍
            synchronized (this) {
                if (index >= values.length) {
                    values = Arrays.copyOf(values, values.length << 1);
                }
            }
        }
        if (value) {
            // 設定為1
            values[index] = values[index] | (1 << offset);
        } else {
            // 設定為 0
            values[index] = values[index] & (~(1 << offset));
        }
    }

    /**
     * 判斷第n個位置是否為1
     */
    public boolean getBit(int n) {
        if (n >= 0 && n < values.length * Integer.SIZE) {
            int index = n / Integer.SIZE;
            int offset = n % Integer.SIZE;
            return ((values[index] >> offset) & 1) == 1;
        }
        return false;
    }

    public static void main(String[] args) {
        /**
         * 1010
         */
        BitMap bit = new BitMap();
        bit.setBit(1, true);
        bit.setBit(3, true);
        System.out.println(bit.getBit(1));
        System.out.println(bit.getBit(2));
        System.out.println(bit.getBit(3));
        bit.setBit(3, false);
        System.out.println("------------------------------------------------");
        System.out.println(bit.getBit(1));
        System.out.println(bit.getBit(2));
        System.out.println(bit.getBit(3));
        System.out.println("------------------------------------------------");
        bit.setBit(63, true);
        // -2147483648
        System.out.println(bit.getBit(63));
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章