Java BitMap

Java BitMap,第1张

至于我为什么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 ? "通过" : "失败"));
  }
}
/*
数量统计检查:通过
数据一致检查:通过
 */

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/2990155.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-23
下一篇 2022-09-23

发表评论

登录后才能评论

评论列表(0条)

保存