import java.util.HashMap;
public class Randompool {
public static class Pool<k> {
private HashMap<k, Integer> keyIndexMap;
private HashMap<Integer, k> inkedexKeyMap;
private int size;
Pool() {
this.keyIndexMap = new HashMap<k, Integer>();
this.inkedexKeyMap = new HashMap<Integer, k>();
this.size = 0;
}
public void insert(k key) {
if (!this.keyIndexMap.containsKey(key)) {
this.keyIndexMap.put(key, this.size);
this.inkedexKeyMap.put(this.size++, key);
}
}
public void delete(k key) {
if (this.keyIndexMap.containsKey(key)) {
int deleteIndex = this.keyIndexMap.get(key);
int lastIndex = --this.size;
k lastKey = this.inkedexKeyMap.get(lastIndex);
this.keyIndexMap.put(lastKey, deleteIndex);
this.inkedexKeyMap.put(deleteIndex, lastKey);
this.keyIndexMap.remove(key);
this.inkedexKeyMap.remove(lastIndex);
}
}
public k getRandom() {
if (this.size == 0)
return null;
int randomIndex = (int)(Math.random() * this.size);
return this.inkedexKeyMap.get(randomIndex);
}
}
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交