网上的一个HashMap代码,用三个数组实现,不同于jdk中的实现方式。处理哈希冲突是采用二次哈希(再哈希)的策略,学习了一把,个别地方可能没有理解到位。写了一些注释,如果有错误,敬请指出。
- public final class LongHashMap {
- protected long table[];//存放键,类型为long,应该是用于特殊场所
- protected Object values[];//存放值
- protected byte state[];//state[i]=0,1,2表示table[i]与values[i]没有使用,已经使用,已删除
- protected int freeEntries;//空闲的空间数
- protected int distinct;//当前存了多少对键值
- protected int lowWaterMark;//当LongHashMap存放的键值对少于此数时,将重新调整(再哈希)
- protected int highWaterMark;//当LongHashMap存放的键值对大于此数时,将重新调整,由容量和装载因子决定
- protected double minLoadFactor;//最小装载因子
- protected double maxLoadFactor;//最大装载因子
- // 如果元素放得太满,就必须进行rehash(再哈希)。再哈希使空间增大,并将原有的对象重新导入新的LongHashMap中,
- //而原始的LongHashMap被删除。loadfactor(装载因子)决定何时要对LongHashMap进行再哈希。
- protected static final int DEFAULT_CAPACITY = 277;//缺省的容量,一个素数
- protected static final double DEFAULT_MIN_LOAD_FACTOR = 0.2;//缺省的最小的装载因子
- protected static final double DEFAULT_MAX_LOAD_FACTOR = 0.6;//缺省的最大的装载因子
- protected static final byte FREE = 0;
- protected static final byte FULL = 1;
- protected static final byte REMOVED = 2;
- //用缺省的容量构建HashMap
- public LongHashMap() {
- this(DEFAULT_CAPACITY);
- }
- //构造函数
- public LongHashMap(int initialCapacity) {
- this(initialCapacity, DEFAULT_MIN_LOAD_FACTOR, DEFAULT_MAX_LOAD_FACTOR);
- }
- //构造函数
- public LongHashMap(int initialCapacity, double minLoadFactor, double maxLoadFactor) {
- setUp(initialCapacity,minLoadFactor,maxLoadFactor);
- }
- //使用指定的初始化容量,最小装载因子,最大装载因子构建LongHashMap
- protected void setUp(int initialCapacity, double minLoadFactor, double maxLoadFactor) {
- if (initialCapacity < 0) {//参数检查
- throw new IllegalArgumentException(
- "Initial Capacity must not be less than zero: "+ initialCapacity
- );
- }
- if (minLoadFactor < 0.0 || minLoadFactor >= 1.0) {
- throw new IllegalArgumentException(
- "Illegal minLoadFactor: "+ minLoadFactor
- );
- }
- if (maxLoadFactor <= 0.0 || maxLoadFactor >= 1.0) {
- throw new IllegalArgumentException(
- "Illegal maxLoadFactor: "+ maxLoadFactor
- );
- }
- if (minLoadFactor >= maxLoadFactor) {
- throw new IllegalArgumentException(
- "Illegal minLoadFactor: " + minLoadFactor +
- " and maxLoadFactor: " + maxLoadFactor
- );
- }
转载于:https://blog.51cto.com/daheyuan/1138492