BitMap java实现

本文介绍了一个名为BitMap的实用工具类的实现细节,该工具类主要用于高效地管理和查询大量布尔值数据。BitMap通过将每个布尔值映射到字节数组中的比特位来节省内存空间,并提供了检查、设置比特位以及获取所有被设置为1的索引等核心功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.jmfy.xianxia.core.util;

import java.util.ArrayList;
import java.util.List;

public class BitMap {
    byte[] bitmap = null;
    int maxIndex = 0;

    //maxIndex 从0开始
    public BitMap(int maxIndex) {
        bitmap = new byte[(maxIndex + 1 + 7) / 8];
        this.maxIndex = maxIndex;
    }

    public boolean checkBit(int index) throws Exception {
        if (index < 0 || index > maxIndex) {
            throw new Exception("index<0 || index=" + index + ">maxIndex=" + maxIndex);
        }
        int byindex = index / 8;
        int btindex = index % 8;
        if ((bitmap[byindex] & (byte) (1 << btindex)) == 0) {
            return false;
        }
        return true;
    }

    public void setBit(int index) throws Exception {
        if (index < 0 || index > maxIndex) {
            throw new Exception("index<0 || index=" + index + ">maxIndex=" + maxIndex);
        }
        int byindex = index / 8;
        int btindex = index % 8;
        bitmap[byindex] = (byte) (bitmap[byindex] | (byte) (1 << btindex));
    }

    public List<Integer> getIntByBit() {
        List<Integer> ids = new ArrayList<>();
        if (bitmap == null) {
            return ids;
        }
        int index = 1;
        for (byte i : bitmap) {
            if ((int) (i & 255) == 0) {
                index += 8;
                continue;
            }
            int temp = 1;
            for (int y = 0; y < 8; y++) {
                if ((int) (i & temp) != 0) {
                    index++;
                    ids.add(index);
                }
                temp = temp << 1;
            }
        }
        return ids;
    }

    public byte getByte(int index) throws Exception {
        if (index < 0 || index > maxIndex) {
            throw new Exception("index<0 || index=" + index + ">maxIndex=" + maxIndex);
        }
        int byindex = index / 8;
        return bitmap[byindex];
    }

    public boolean isEmpty() {
        int byCount = (maxIndex + 1 + 7) / 8;
        for (int i = 0; i < byCount; i++) {
            if (bitmap[i] != 0) {
                return false;
            }
        }
        return true;
    }
}
### 如何用 Java 实现 Bitmap 签到功能 为了实现基于 Redis 的 Bitmap 用户签到功能,可以通过 Spring Data Redis 来集成 Redis 并利用其提供的 Bitmap 数据结构。以下是完整的代码示例以及相关说明。 #### 1. 添加依赖 首先,在项目中引入必要的 Maven 或 Gradle 依赖项来支持 Redis 和 Spring Data Redis: ```xml <!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> ``` 或者使用 Gradle: ```gradle implementation 'org.springframework.boot:spring-boot-starter-data-redis' implementation 'com.fasterxml.jackson.core:jackson-databind' ``` --- #### 2. 配置 Redis 连接 配置 `application.yml` 文件中的 Redis 参数: ```yaml spring: redis: host: localhost port: 6379 password: lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0 ``` --- #### 3. 编写签到逻辑代码 下面是一个简单的签到功能实现代码示例: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.time.LocalDate; @Service public class CheckInService { @Autowired private StringRedisTemplate stringRedisTemplate; /** * 用户签到方法 * * @param userId 用户ID */ public void checkIn(String userId) { LocalDate today = LocalDate.now(); long dayOfYear = today.getLong(java.time.temporal.ChronoField.DAY_OF_YEAR); stringRedisTemplate.opsForValue().setBit(userId, dayOfYear, true); // 设置当前日期对应的 bit 值为 1 [^4] } /** * 查询某天是否已签到 * * @param userId 用户ID * @param date 要查询的日期 * @return 是否已签到 */ public boolean isCheckedInOnDate(String userId, LocalDate date) { long dayOfYear = date.getLong(java.time.temporal.ChronoField.DAY_OF_YEAR); return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().getBit(userId, dayOfYear)); // 获取指定日期的 bit 值 } /** * 统计连续签到天数 * * @param userId 用户ID * @return 连续签到天数 */ public int countConsecutiveCheckIns(String userId) { LocalDate today = LocalDate.now(); long currentDay = today.getLong(java.time.temporal.ChronoField.DAY_OF_YEAR); int consecutiveDays = 0; while (currentDay >= 0 && Boolean.TRUE.equals(stringRedisTemplate.opsForValue().getBit(userId, currentDay))) { // 循环判断连续签到情况 consecutiveDays++; currentDay--; } return consecutiveDays; } } ``` --- #### 4. 测试代码 编写单元测试验证签到功能是否正常运行: ```java @SpringBootTest class CheckInServiceTest { @Autowired private CheckInService checkInService; @Test void testCheckIn() { String userId = "testUser"; // 执行签到 checkInService.checkIn(userId); // 验证当天是否已签到 assertTrue(checkInService.isCheckedInOnDate(userId, LocalDate.now())); // 计算连续签到天数 assertEquals(1, checkInService.countConsecutiveCheckIns(userId)); } } ``` --- #### 关键点解析 1. **存储优化** 使用 Bitmap 存储用户的签到记录能够显著减少内存消耗。例如,每月仅需 4 字节即可保存每天的签到状态[^3]。 2. **高效操作** Redis 提供了专门的操作命令(如 SETBIT、GETBIT),可以直接对位图进行设置和读取,性能极高。 3. **扩展性** 如果系统是分布式的,则可以选择 Redis 作为集中化的存储方案,便于跨服务访问和管理[^1]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值