
shz.st.hst.LinearProbingHST Maven / Gradle / Ivy
package shz.st.hst;
/**
* 基于线性探测的散列表(开放地址法)
*
* 需保证使用率在1/8到1/2之间
*/
@SuppressWarnings("unchecked")
public class LinearProbingHST extends HST {
protected K[] keys;
protected V[] vales;
protected LinearProbingHST(int capacity) {
super(capacity);
keys = (K[]) new Object[capacity];
vales = (V[]) new Object[capacity];
}
public static LinearProbingHST of(int capacity) {
return new LinearProbingHST<>(capacity);
}
public static LinearProbingHST of() {
return of(DEFAULT_CAPACITY);
}
@Override
protected final void resize(int capacity) {
LinearProbingHST t = LinearProbingHST.of(capacity);
for (int i = 0; i < this.capacity; ++i) if (keys[i] != null) t.put(keys[i], vales[i]);
keys = t.keys;
vales = t.vales;
this.capacity = t.capacity;
}
public final void put(K key, V val) {
if (key == null) throw new NullPointerException();
beforePut();
int i;
for (i = hash(key); keys[i] != null; i = (i + 1) % capacity) {
if (keys[i].equals(key)) {
vales[i] = val;
return;
}
}
keys[i] = key;
vales[i] = val;
++size;
}
protected final int hash(K key) {
return (key.hashCode() & 0x7fffffff) % capacity;
}
public final V get(K key) {
for (int i = hash(key); keys[i] != null; i = (i + 1) % capacity) if (keys[i].equals(key)) return vales[i];
return null;
}
public final boolean containsKey(K key) {
for (int i = hash(key); keys[i] != null; i = (i + 1) % capacity) if (keys[i].equals(key)) return true;
return false;
}
public final void delete(K key) {
if (key == null) throw new NullPointerException();
int i = hash(key);
for (; keys[i] != null; i = (i + 1) % capacity) if (keys[i].equals(key)) break;
if (keys[i] == null) return;
keys[i] = null;
vales[i] = null;
i = (i + 1) % capacity;
while (keys[i] != null) {
K keyToRedo = keys[i];
V valToRedo = vales[i];
keys[i] = null;
vales[i] = null;
--size;
put(keyToRedo, valToRedo);
i = (i + 1) % capacity;
}
--size;
if (size > 0 && size <= capacity >>> 3) resize(capacity >> 1);
}
}