在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));
}
}