-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathHashTable.java
102 lines (81 loc) · 2.56 KB
/
HashTable.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package hash_table;
import java.util.TreeMap;
public class HashTable<K, V> {
private final int[] capacity
= {53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593,
49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469,
12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741};
public static final int UPPER_TOL = 10;
public static final int LOWER_TOL = 2;
public int capacity_index;
private TreeMap<K, V>[] hashTable;
private int size;
private int M;
public HashTable() {
this.M = capacity[capacity_index];
hashTable = new TreeMap[M];
for (int i = 0; i < M; i++) {
hashTable[i] = new TreeMap<>();
}
}
private int hash(K k) {
return (k.hashCode() & 0x7fffffff) % M;
}
public int getSize() {
return size;
}
public boolean contains(K k) {
return hashTable[hash(k)].containsKey(k);
}
public void add(K k, V v) {
TreeMap<K, V> treeMap = hashTable[hash(k)];
if (treeMap.containsKey(k)) {
treeMap.put(k, v);
} else {
treeMap.put(k, v);
size++;
if (size > UPPER_TOL * M && capacity_index < capacity.length - 1) {
capacity_index++;
resize(capacity_index);
}
}
}
public V remove(K k) {
TreeMap<K, V> treeMap = hashTable[hash(k)];
V ret = null;
if (treeMap.containsKey(k)) {
ret = treeMap.remove(k);
size--;
if (size < LOWER_TOL * M && capacity_index - 1 >= 0) {
capacity_index--;
resize(capacity_index);
}
}
return ret;
}
public V set(K k, V v) {
TreeMap<K, V> treeMap = hashTable[hash(k)];
if (!treeMap.containsKey(k)) {
throw new IllegalArgumentException(k + "doesn't exist~");
}
return treeMap.put(k, v);
}
public V get(K k) {
return hashTable[hash(k)].get(k);
}
private void resize(int newCapacity) {
TreeMap[] newHashTable = new TreeMap[newCapacity];
for (int i = 0; i < newCapacity; i++) {
newHashTable[i] = new TreeMap();
}
int oldM = M;
M = newCapacity;
for (int i = 0; i < oldM; i++) {
TreeMap<K, V> treeMap = hashTable[i];
for (K k : treeMap.keySet()) {
newHashTable[hash(k)].put(k, treeMap.get(k));
}
}
hashTable = newHashTable;
}
}