-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashedDictionary.java
More file actions
561 lines (398 loc) · 14.7 KB
/
HashedDictionary.java
File metadata and controls
561 lines (398 loc) · 14.7 KB
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
import java.util.Iterator;
import java.util.NoSuchElementException;
public class HashedDictionary<K, V> implements DictionaryInterface<K, V>
{
// The dictionary:
private int numberOfEntries;
private static final int DEFAULT_CAPACITY = 5; // Must be prime
private static final int MAX_CAPACITY = 10000;
// The hash table:
private TableEntry<K, V>[] hashTable;
private int tableSize; // Must be prime
private static final int MAX_SIZE = 2 * MAX_CAPACITY;
private boolean initialized = false;
private static final double MAX_LOAD_FACTOR = 0.5; // Fraction of hash table that can be filled
public HashedDictionary(){
this(DEFAULT_CAPACITY); // Call next constructor
} // end default constructor
public HashedDictionary(int initialCapacity){
checkCapacity(initialCapacity);
numberOfEntries = 0; // Dictionary is empty
// Set up hash table:
// Initial size of hash table is same as initialCapacity if it is prime;
// otherwise increase it until it is prime size
int tableSize = getNextPrime(initialCapacity);
checkSize(tableSize);
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
TableEntry<K, V>[] temp = (TableEntry<K, V>[])new TableEntry[tableSize];
hashTable = temp;
initialized = true;
} // end constructor
// -------------------------
// We've added this method to display the hash table for illustration and testing
// -------------------------
public void displayHashTable(){
checkInitialization();
for (int index = 0; index < hashTable.length; index++) {
if (hashTable[index] == null)
System.out.println("null ");
else if (hashTable[index].isRemoved())
System.out.println("removed state");
else
System.out.println(hashTable[index].getKey() + " " + hashTable[index].getValue());
} // end for
System.out.println();
} // end displayHashTable
// -------------------------
public V add(K key, V value){
//You need to write "add" method
checkInitialization();
if ((key == null) || (value == null)){
throw new IllegalArgumentException();
}
else{
V oldValue;
int i = getHashIndex(key);
i = probe(i, key);
assert (i >=0) && (i < hashTable.length);
if ( (hashTable[i] == null) || hashTable[i].isRemoved()){
//key not found, so insert new entry
hashTable[i] = new TableEntry<>(key, value);
numberOfEntries++;
oldValue = null;
}
else{
//key found; get old value for return and then replace it
oldValue = hashTable[i].getValue();
hashTable[i].setValue(value);
}
//ensure that hash table is large enough for another add
if (isHashTableTooFull()){
enlargeHashTable();
}
return oldValue;
}
} // end add
public V remove(K key){
//You need to write "remove" method
checkInitialization();
V removedValue = null;
int i=getHashIndex(key);
i = locate(i, key);
if (i != -1){
removedValue = hashTable[i].getValue();
hashTable[i].setToRemoved();
numberOfEntries--;
}
return removedValue;
} // end remove
public V getValue(K key){
//You need to write "getValue" method
checkInitialization();
V result = null;
int i = getHashIndex(key);
i = locate(i, key);
if (i != -1){
result = hashTable[i].getValue();
}
return result;
} // end getValue
public boolean contains(K key){
//You need to write "contains" method
return getValue(key) != null;
} // end contains
public boolean isEmpty(){
//You need to write "isEmpty" method
return numberOfEntries == 0;
} // end isEmpty
public int getSize(){
//You need to write "getSize" method
return numberOfEntries;
} // end getSize
public final void clear(){
//You need to write "clear" method
checkInitialization();;
for (int i=0; i<hashTable.length; i++){
hashTable[i] = null;
}
numberOfEntries = 0;
} // end clear
public Iterator<K> getKeyIterator(){
//You need to write "getKeyIterator" method
return new KeyIterator();
} // end getKeyIterator
public Iterator<V> getValueIterator(){
//You need to write "getValueIterator" method
return new ValueIterator();
} // end getValueIterator
private int getHashIndex(K key)
{
int hashIndex = key.hashCode() % hashTable.length;
if (hashIndex < 0){
hashIndex = hashIndex + hashTable.length;
} // end if
return hashIndex;
} // end getHashIndex
// Precondition: checkInitialization has been called.
private int probe(int index, K key)
{
boolean found = false;
int removedStateIndex = -1; // Index of first location in removed state
// int increment = 1; // For quadratic probing **********
while ( !found && (hashTable[index] != null) )
{
if (hashTable[index].isIn()){
if (key.equals(hashTable[index].getKey()))
found = true; // Key found
else // Follow probe sequence
index = (index + 1) % hashTable.length; // Linear probing
// index = (index + increment) % hashTable.length; // Quadratic probing **********
// increment = increment + 2; // Odd values for quadratic probing **********
}
else // Skip entries that were removed
{
// Save index of first location in removed state
if (removedStateIndex == -1)
removedStateIndex = index;
index = (index + 1) % hashTable.length; // Linear probing
// index = (index + increment) % hashTable.length; // Quadratic probing **********
// increment = increment + 2; // Odd values for quadratic probing **********
} // end if
} // end while
// Assertion: Either key or null is found at hashTable[index]
if (found || (removedStateIndex == -1) )
return index; // Index of either key or null
else
return removedStateIndex; // Index of an available location
} // end probe
// Precondition: checkInitialization has been called.
private int locate(int index, K key)
{
boolean found = false;
// int increment = 1; // Quadratic probing **********
while ( !found && (hashTable[index] != null) )
{
if ( hashTable[index].isIn() && key.equals(hashTable[index].getKey()) )
found = true; // Key found
else // Follow probe sequence
index = (index + 1) % hashTable.length; // Linear probing
// index = (index + increment) % hashTable.length; // Quadratic probing **********
// increment = increment + 2; // Odd values for quadratic probing **********
} // end while
// Assertion: Either key or null is found at hashTable[index]
int result = -1;
if (found)
result = index;
return result;
} // end locate
// Increases the size of the hash table to a prime >= twice its old size.
// In doing so, this method must rehash the table entries.
// Precondition: checkInitialization has been called.
private void enlargeHashTable()
{
TableEntry<K, V>[] oldTable = hashTable;
int oldSize = hashTable.length;
int newSize = getNextPrime(oldSize + oldSize);
checkSize(newSize);
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
TableEntry<K, V>[] tempTable = (TableEntry<K, V>[])new TableEntry[newSize]; // Increase size of array
hashTable = tempTable;
numberOfEntries = 0; // Reset number of dictionary entries, since
// it will be incremented by add during rehash
// Rehash dictionary entries from old array to the new and bigger array;
// skip both null locations and removed entries
for (int index = 0; index < oldSize; index++){
if ( (oldTable[index] != null) && oldTable[index].isIn() )
add(oldTable[index].getKey(), oldTable[index].getValue());
} // end for
} // end enlargeHashTable
// Returns true if lambda > MAX_LOAD_FACTOR for hash table;
// otherwise returns false.
private boolean isHashTableTooFull()
{
return numberOfEntries > MAX_LOAD_FACTOR * hashTable.length;
} // end isHashTableTooFull
// Returns a prime integer that is >= the given integer.
private int getNextPrime(int integer)
{
// if even, add 1 to make odd
if (integer % 2 == 0){
integer++;
} // end if
// test odd integers
while (!isPrime(integer))
{
integer = integer + 2;
} // end while
return integer;
} // end getNextPrime
// Returns true if the given integer is prime.
private boolean isPrime(int integer)
{
boolean result;
boolean done = false;
// 1 and even numbers are not prime
if ( (integer == 1) || (integer % 2 == 0) ){
result = false;
}
// 2 and 3 are prime
else if ( (integer == 2) || (integer == 3) ){
result = true;
}
else { // integer is odd and >= 5
assert (integer % 2 != 0) && (integer >= 5);
// a prime is odd and not divisible by every odd integer up to its square root
result = true; // assume prime
for (int divisor = 3; !done && (divisor * divisor <= integer); divisor = divisor + 2){
if (integer % divisor == 0){
result = false; // divisible; not prime
done = true;
} // end if
} // end for
} // end if
return result;
} // end isPrime
// Throws an exception if this object is not initialized.
private void checkInitialization()
{
if (!initialized)
throw new SecurityException ("HashedDictionary object is not initialized properly.");
} // end checkInitialization
// Ensures that the client requests a capacity
// that is not too small or too large.
private void checkCapacity(int capacity)
{
if (capacity < DEFAULT_CAPACITY)
capacity = DEFAULT_CAPACITY;
else if (capacity > MAX_CAPACITY)
throw new IllegalStateException("Attempt to create a dictionary " +
"whose capacity is larger than " +
MAX_CAPACITY);
} // end checkCapacity
// Throws an exception if the hash table becomes too large.
private void checkSize(int size)
{
if (tableSize > MAX_SIZE)
throw new IllegalStateException("Dictionary has become too large.");
} // end checkSize
private class KeyIterator implements Iterator<K>
{
private int currentIndex; // Current position in hash table
private int numberLeft; // Number of entries left in iteration
private KeyIterator()
{
currentIndex = 0;
numberLeft = numberOfEntries;
} // end default constructor
public boolean hasNext()
{
return numberLeft > 0;
} // end hasNext
public K next()
{
K result = null;
if (hasNext()){
// Skip table locations that do not contain a current entry
while ( (hashTable[currentIndex] == null) || hashTable[currentIndex].isRemoved() )
{
currentIndex++;
} // end while
result = hashTable[currentIndex].getKey();
numberLeft--;
currentIndex++;
}
else
throw new NoSuchElementException();
return result;
} // end next
public void remove()
{
throw new UnsupportedOperationException();
} // end remove
} // end KeyIterator
private class ValueIterator implements Iterator<V>
{
private int currentIndex;
private int numberLeft;
private ValueIterator()
{
currentIndex = 0;
numberLeft = numberOfEntries;
} // end default constructor
public boolean hasNext()
{
return numberLeft > 0;
} // end hasNext
public V next()
{
V result = null;
if (hasNext())
{
// Skip table locations that do not contain a current entry
while ( (hashTable[currentIndex] == null) || hashTable[currentIndex].isRemoved() )
{
currentIndex++;
} // end while
result = hashTable[currentIndex].getValue();
numberLeft--;
currentIndex++;
}
else
throw new NoSuchElementException();
return result;
} // end next
public void remove()
{
throw new UnsupportedOperationException();
} // end remove
} // end ValueIterator
private static class TableEntry<S, T>
{
private S key;
private T value;
private States state; // Flags whether this entry is in the hash table
private enum States {CURRENT, REMOVED} // Possible values of state
private TableEntry(S searchKey, T dataValue)
{
key = searchKey;
value = dataValue;
state = States.CURRENT;
} // end constructor
private S getKey()
{
return key;
} // end getKey
private T getValue()
{
return value;
} // end getValue
private void setValue(T newValue)
{
value = newValue;
} // end setValue
// Returns true if this entry is currently in the hash table.
private boolean isIn()
{
return state == States.CURRENT;
} // end isIn
// Returns true if this entry has been removed from the hash table.
private boolean isRemoved()
{
return state == States.REMOVED;
} // end isRemoved
// Sets the state of this entry to be removed.
private void setToRemoved()
{
key = null;
value = null;
state = States.REMOVED; // Entry not in use, ie deleted from table
} // end setToRemoved
// Sets the state of this entry to current.
private void setToIn() // Not used
{
state = States.CURRENT; // Entry in use
} // end setToIn
} // end TableEntry
} // end HashedDictionary