1 22 23 package com.sosnoski.util; 24 25 import java.lang.reflect.Array ; 26 27 62 63 public abstract class PrimitiveHashBase 64 { 65 66 protected static final double DEFAULT_FILL = 0.3d; 67 68 69 protected static final int MINIMUM_SIZE = 31; 70 71 72 protected static final int KEY_MULTIPLIER = 517; 73 74 75 protected double m_fillFraction; 76 77 78 protected int m_entryCount; 79 80 81 protected int m_entryLimit; 82 83 84 protected int m_hitOffset; 85 86 87 protected boolean[] m_flagTable; 88 89 96 97 public PrimitiveHashBase(int count, double fill, Class ktype) { 98 99 if (fill <= 0.0d || fill >= 1.0d) { 101 throw new IllegalArgumentException ("fill value out of range"); 102 } 103 m_fillFraction = fill; 104 105 int size = Math.max((int) (count / m_fillFraction), MINIMUM_SIZE); 107 size += (size + 1) % 2; 108 109 m_entryLimit = (int) (size * m_fillFraction); 111 m_hitOffset = size / 2; 112 m_flagTable = new boolean[size]; 113 setKeyArray(Array.newInstance(ktype, size)); 114 } 115 116 121 122 public PrimitiveHashBase(PrimitiveHashBase base) { 123 124 m_fillFraction = base.m_fillFraction; 126 m_entryCount = base.m_entryCount; 127 m_entryLimit = base.m_entryLimit; 128 m_hitOffset = base.m_hitOffset; 129 130 int size = base.m_flagTable.length; 132 m_flagTable = new boolean[size]; 133 System.arraycopy(base.m_flagTable, 0, m_flagTable, 0, 134 m_flagTable.length); 135 136 Class type = base.getKeyArray().getClass().getComponentType(); 138 Object copy = Array.newInstance(type, size); 139 System.arraycopy(base.getKeyArray(), 0, copy, 0, size); 140 setKeyArray(copy); 141 } 142 143 148 149 public final int size() { 150 return m_entryCount; 151 } 152 153 160 161 protected abstract Object getKeyArray(); 162 163 170 171 protected abstract void setKeyArray(Object array); 172 173 181 182 protected abstract void reallocate(int size); 183 184 190 191 protected void growCapacity(int min) { 192 193 int size = m_flagTable.length; 195 int limit = m_entryLimit; 196 while (limit < min) { 197 size = size * 2 + 1; 198 limit = (int) (size * m_fillFraction); 199 } 200 201 m_entryLimit = limit; 203 m_hitOffset = size / 2; 204 205 reallocate(size); 207 } 208 209 215 216 public final void ensureCapacity(int min) { 217 if (min > m_entryLimit) { 218 growCapacity(min); 219 } 220 } 221 222 227 228 public void clear() { 229 for (int i = 0; i < m_flagTable.length; i++) { 230 m_flagTable[i] = false; 231 } 232 m_entryCount = 0; 233 } 234 235 242 243 protected final int stepSlot(int slot) { 244 return (slot + m_hitOffset) % m_flagTable.length; 245 } 246 247 256 257 protected final int freeSlot(int slot) { 258 while (m_flagTable[slot]) { 259 slot = stepSlot(slot); 260 } 261 return slot; 262 } 263 } 264 | Popular Tags |