用int数组表示bit数组

在Java泛型中,
?:不确定的Java类型
T:Java类型
K,V:java键值中的key和value
E:Element

1、利用哈希表实现一个结构:RandomPool结构

package day1;

import java.util.HashMap;

public class Demo {
    public static class Pool<K>{//泛型
        private HashMap<K,Integer> keyIndexMap;
        private HashMap<Integer,K> indexKeyMap;
        private int size;

        public Pool(){
            keyIndexMap=new HashMap<>();
            indexKeyMap=new HashMap<>();
            size=0;
        }

        public void insert(K key){
            if(!keyIndexMap.containsKey(key)){
                keyIndexMap.put(key,size);
                indexKeyMap.put(size,key);
                size++;
            }
        }

        public void delete(K key){
            if(keyIndexMap.containsKey(key)) {
                size--;
                Integer deleteIndex=keyIndexMap.get(key);//要删除字符串对应的序号
                K lastKey=indexKeyMap.get(size);//最后一个字符串
                keyIndexMap.put(lastKey,deleteIndex);
                indexKeyMap.put(deleteIndex,lastKey);
                keyIndexMap.remove(key);
                indexKeyMap.remove(size);
            }
        }

        public  K getRandom(){
            if(size==0){
                return null;
            }

            return indexKeyMap.get((int)Math.random()*size);
        }

    }
    public static void main(String[] args) {
        Pool<String> pool =new Pool<>();
        pool.insert("zuo");
        pool.insert("cheng");
        pool.insert("yun");
        System.out.println(pool.getRandom());
    }
}

2、利用int数组表现bit数组

package day1;

public class Demo {

    public static void main(String[] args) {
        int[] arr=new int[10];//320 bits
        //arr[0] 0-31 bit

        int i=178;//bit[] b; b[178] 为b中第179个数

        int numIndex=i/32;//arr[5]
        int bitIndex=i%32;//18-> arr[5]中的[18] 即第19个数

        //拿到178位的状态
        int s=(arr[numIndex]>>bitIndex)&1;

        //把178位状态改为1
        arr[numIndex]=arr[numIndex]|(1<<bitIndex);

        //把178位状态改为0 & 此位&0 其余都1
        arr[numIndex]=arr[numIndex]&(~(1<<bitIndex));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值