Java BitMap

8 篇文章 0 订阅
2 篇文章 0 订阅

至于我为什么long数组而不是直接用bool数组,是为了实现创建突破数组长度上限的BitMap长度

class BitMap {
  public final long MapLength;
  private final long[] bitMap;
  private final byte unitLength = Long.SIZE;

  public BitMap(Long mapLength) {
    MapLength = mapLength;
    int mapArrLength = (int) (mapLength / unitLength);
    if (((long) mapArrLength * unitLength) < mapLength) mapArrLength++;
    bitMap = new long[mapArrLength];
  }

  public boolean read(long index) {
    return read((int) (index / unitLength), (byte) (index % unitLength));
  }

  private boolean read(int mapIndex, byte byteIndex) {
    return (bitMap[mapIndex] & (1L << byteIndex)) != 0;
  }

  public void write(long index, boolean value) {
    int mapIndex = (int) (index / unitLength);
    byte byteIndex = (byte) (index % unitLength);
    boolean before = read(mapIndex, byteIndex);
    if (value == before) return;
    if (before) bitMap[mapIndex] ^= 1L << byteIndex;
    else bitMap[mapIndex] |= 1L << byteIndex;
  }

  public void writeTrue(long index) {
    write(index, true);
  }

  public void writeFalse(long index) {
    write(index, false);
  }

  public long count() {
    long count = 0;
    for (long j : bitMap) count += Long.bitCount(j);
    return count;
  }
}

public class Main {
  public static void main(String[] args) {
    long checkLength = 10000000L;
    BitMap bm = new BitMap(checkLength);
    boolean[] ans = new boolean[(int) checkLength];

    long c0 = 0;
    for (int i = 0; i < bm.MapLength; i++) {
      if (Math.random() > 0.5) {
        bm.write(i, true);
        ans[i] = true;
        c0 += 1;
      }
    }

    long c1 = bm.count();
    System.out.println("数量统计检查:" + (c0 == c1 ? "通过" : "失败"));

    boolean successFlag = true;
    for (int i = 0; i < ans.length; i++) {
      if (ans[i] ^ bm.read(i)) {
        System.out.println("在" + i + "出现错误");
        successFlag = false;
        break;
      }
    }
    System.out.println("数据一致检查:" + (successFlag ? "通过" : "失败"));
  }
}
/*
数量统计检查:通过
数据一致检查:通过
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值