/
HashTableSeparateChaining.java
280 lines (225 loc) · 8.14 KB
/
HashTableSeparateChaining.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/**
* An implementation of a hash-table using separate chaining with a linked list.
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.datastructures.hashtable;
import java.util.*;
class Entry<K, V> {
int hash;
K key;
V value;
public Entry(K key, V value) {
this.key = key;
this.value = value;
this.hash = key.hashCode();
}
// We are not overriding the Object equals method
// No casting is required with this method.
public boolean equals(Entry<K, V> other) {
if (hash != other.hash) return false;
return key.equals(other.key);
}
@Override
public String toString() {
return key + " => " + value;
}
}
@SuppressWarnings("unchecked")
public class HashTableSeparateChaining<K, V> implements Iterable<K> {
private static final int DEFAULT_CAPACITY = 3;
private static final double DEFAULT_LOAD_FACTOR = 0.75;
private double maxLoadFactor;
private int capacity, threshold, size = 0;
private LinkedList<Entry<K, V>>[] table;
public HashTableSeparateChaining() {
this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public HashTableSeparateChaining(int capacity) {
this(capacity, DEFAULT_LOAD_FACTOR);
}
// Designated constructor
public HashTableSeparateChaining(int capacity, double maxLoadFactor) {
if (capacity < 0) throw new IllegalArgumentException("Illegal capacity");
if (maxLoadFactor <= 0 || Double.isNaN(maxLoadFactor) || Double.isInfinite(maxLoadFactor))
throw new IllegalArgumentException("Illegal maxLoadFactor");
this.maxLoadFactor = maxLoadFactor;
this.capacity = Math.max(DEFAULT_CAPACITY, capacity);
threshold = (int) (this.capacity * maxLoadFactor);
table = new LinkedList[this.capacity];
}
// Returns the number of elements currently inside the hash-table
public int size() {
return size;
}
// Returns true/false depending on whether the hash-table is empty
public boolean isEmpty() {
return size == 0;
}
// Converts a hash value to an index. Essentially, this strips the
// negative sign and places the hash value in the domain [0, capacity)
private int normalizeIndex(int keyHash) {
return (keyHash & 0x7FFFFFFF) % capacity;
}
// Clears all the contents of the hash-table
public void clear() {
Arrays.fill(table, null);
size = 0;
}
public boolean containsKey(K key) {
return hasKey(key);
}
// Returns true/false depending on whether a key is in the hash table
public boolean hasKey(K key) {
int bucketIndex = normalizeIndex(key.hashCode());
return bucketSeekEntry(bucketIndex, key) != null;
}
// Insert, put and add all place a value in the hash-table
public V put(K key, V value) {
return insert(key, value);
}
public V add(K key, V value) {
return insert(key, value);
}
public V insert(K key, V value) {
if (key == null) throw new IllegalArgumentException("Null key");
Entry<K, V> newEntry = new Entry<>(key, value);
int bucketIndex = normalizeIndex(newEntry.hash);
return bucketInsertEntry(bucketIndex, newEntry);
}
// Gets a key's values from the map and returns the value.
// NOTE: returns null if the value is null AND also returns
// null if the key does not exists, so watch out..
public V get(K key) {
if (key == null) return null;
int bucketIndex = normalizeIndex(key.hashCode());
Entry<K, V> entry = bucketSeekEntry(bucketIndex, key);
if (entry != null) return entry.value;
return null;
}
// Removes a key from the map and returns the value.
// NOTE: returns null if the value is null AND also returns
// null if the key does not exists.
public V remove(K key) {
if (key == null) return null;
int bucketIndex = normalizeIndex(key.hashCode());
return bucketRemoveEntry(bucketIndex, key);
}
// Removes an entry from a given bucket if it exists
private V bucketRemoveEntry(int bucketIndex, K key) {
Entry<K, V> entry = bucketSeekEntry(bucketIndex, key);
if (entry != null) {
LinkedList<Entry<K, V>> links = table[bucketIndex];
links.remove(entry);
--size;
return entry.value;
} else return null;
}
// Inserts an entry in a given bucket only if the entry does not already
// exist in the given bucket, but if it does then update the entry value
private V bucketInsertEntry(int bucketIndex, Entry<K, V> entry) {
LinkedList<Entry<K, V>> bucket = table[bucketIndex];
if (bucket == null) table[bucketIndex] = bucket = new LinkedList<>();
Entry<K, V> existentEntry = bucketSeekEntry(bucketIndex, entry.key);
if (existentEntry == null) {
bucket.add(entry);
if (++size > threshold) resizeTable();
return null; // Use null to indicate that there was no previous entry
} else {
V oldVal = existentEntry.value;
existentEntry.value = entry.value;
return oldVal;
}
}
// Finds and returns a particular entry in a given bucket if it exists, returns null otherwise
private Entry<K, V> bucketSeekEntry(int bucketIndex, K key) {
if (key == null) return null;
LinkedList<Entry<K, V>> bucket = table[bucketIndex];
if (bucket == null) return null;
for (Entry<K, V> entry : bucket) if (entry.key.equals(key)) return entry;
return null;
}
// Resizes the internal table holding buckets of entries
private void resizeTable() {
capacity *= 2;
threshold = (int) (capacity * maxLoadFactor);
LinkedList<Entry<K, V>>[] newTable = new LinkedList[capacity];
for (int i = 0; i < table.length; i++) {
if (table[i] != null) {
for (Entry<K, V> entry : table[i]) {
int bucketIndex = normalizeIndex(entry.hash);
LinkedList<Entry<K, V>> bucket = newTable[bucketIndex];
if (bucket == null) newTable[bucketIndex] = bucket = new LinkedList<>();
bucket.add(entry);
}
// Avoid memory leak. Help the GC
table[i].clear();
table[i] = null;
}
}
table = newTable;
}
// Returns the list of keys found within the hash table
public List<K> keys() {
List<K> keys = new ArrayList<>(size());
for (LinkedList<Entry<K, V>> bucket : table)
if (bucket != null) for (Entry<K, V> entry : bucket) keys.add(entry.key);
return keys;
}
// Returns the list of values found within the hash table
public List<V> values() {
List<V> values = new ArrayList<>(size());
for (LinkedList<Entry<K, V>> bucket : table)
if (bucket != null) for (Entry<K, V> entry : bucket) values.add(entry.value);
return values;
}
// Return an iterator to iterate over all the keys in this map
@Override
public java.util.Iterator<K> iterator() {
final int elementCount = size();
return new java.util.Iterator<K>() {
int bucketIndex = 0;
java.util.Iterator<Entry<K, V>> bucketIter = (table[0] == null) ? null : table[0].iterator();
@Override
public boolean hasNext() {
// An item was added or removed while iterating
if (elementCount != size) throw new java.util.ConcurrentModificationException();
// No iterator or the current iterator is empty
if (bucketIter == null || !bucketIter.hasNext()) {
// Search next buckets until a valid iterator is found
while (++bucketIndex < capacity) {
if (table[bucketIndex] != null) {
// Make sure this iterator actually has elements -_-
java.util.Iterator<Entry<K, V>> nextIter = table[bucketIndex].iterator();
if (nextIter.hasNext()) {
bucketIter = nextIter;
break;
}
}
}
}
return bucketIndex < capacity;
}
@Override
public K next() {
return bucketIter.next().key;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
// Returns a string representation of this hash table
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
for (int i = 0; i < capacity; i++) {
if (table[i] == null) continue;
for (Entry<K, V> entry : table[i]) sb.append(entry + ", ");
}
sb.append("}");
return sb.toString();
}
}