-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
HashMap.java
916 lines (784 loc) · 24.1 KB
/
HashMap.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
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
package com.jwetherell.algorithms.data_structures;
import java.util.ArrayList;
import java.util.List;
import com.jwetherell.algorithms.data_structures.interfaces.IMap;
/**
* Hash Map using either chaining or probing. hash map is a data structure that
* uses a hash function to map identifying values, known as keys, to their
* associated values.
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Hash_table">Hash Map/Table (Wikipedia)</a>
* <br>
* @author Justin Wetherell <[email protected]>
*/
@SuppressWarnings("unchecked")
public class HashMap<K, V> implements IMap<K,V> {
public static enum Type { CHAINING, PROBING }
private HashMap<K,V> delegateMap = null;
private static class ChainingHashMap<K, V> extends HashMap<K, V> {
private float loadFactor = 10.0f;
private int minimumSize = 1024;
private int initialListSize = 10;
private List<Pair<K, V>>[] array = null;
private int size = 0;
/**
* Create a hash map with K as the hashing key.
*
* @param size
* initial size.
*/
public ChainingHashMap(int size) {
initializeMap(size);
}
/**
* Create a hash map with the default hashing key.
*/
public ChainingHashMap() {
initializeMap(minimumSize);
}
/**
* {@inheritDoc}
*/
@Override
public V put(K key, V value) {
return put(new Pair<K, V>(key, value));
}
public V put(Pair<K,V> newPair) {
int index = indexOf(newPair.key.hashCode());
List<Pair<K, V>> list = array[index];
V prev = null;
boolean exist = false;
// Do not add duplicates
for (Pair<K, V> p : list) {
if (p.key.equals(newPair.key)) {
prev = p.value;
p.value = newPair.value;
exist = true;
break;
}
}
if (!exist)
list.add(newPair);
size++;
// If size is greater than threshold
int maxSize = (int)(loadFactor*array.length);
if (size >= maxSize)
increase();
return prev;
}
/**
* {@inheritDoc}
*/
@Override
public V get(K key) {
int index = indexOf(key.hashCode());
List<Pair<K, V>> list = array[index];
for (Pair<K, V> p : list) {
if (p.key.equals(key))
return p.value;
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(K key) {
return (get(key)!=null);
}
/**
* {@inheritDoc}
*/
@Override
public V remove(K key) {
int index = indexOf(key.hashCode());
List<Pair<K, V>> list = array[index];
for (Pair<K, V> pair : list) {
if (pair.key.equals(key)) {
list.remove(pair);
size--;
V value = pair.value;
pair.key = null;
pair.value = null;
int loadFactored = (int)(size/loadFactor);
int smallerSize = getSmallerSize(array.length);
if (loadFactored < smallerSize && smallerSize > minimumSize)
reduce();
return value;
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
for (int i=0; i<array.length; i++)
array[i].clear();
size = 0;
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return size;
}
private void increase() {
// Save old data
List<Pair<K, V>>[] temp = this.array;
// Calculate new size and assign
int length = getLargerSize(array.length);
//System.out.println("increase from "+array.length+" to "+length);
initializeMap(length);
// Re-hash old data
for (List<Pair<K, V>> list : temp) {
for (Pair<K, V> p :list) {
this.put(p);
}
}
}
private void reduce() {
// Save old data
List<Pair<K, V>>[] temp = this.array;
// Calculate new size and check minimum
int length = getSmallerSize(array.length);
//System.out.println("reduce from "+array.length+" to "+length);
initializeMap(length);
// Re-hash old data
for (List<Pair<K, V>> list : temp) {
for (Pair<K, V> p :list) {
this.put(p);
}
}
}
/**
* Increases the input ten-fold. e.g. 16->160
*/
private static final int getLargerSize(int input) {
return input*10;
}
/**
* Returns one fourth of the input. e.g. 16->4
*/
private static final int getSmallerSize(int input) {
return input/4;
}
/**
* Initialize the hash array.
*/
private void initializeMap(int length) {
this.array = new ArrayList[length];
for (int i = 0; i < array.length; i++)
this.array[i] = new ArrayList<Pair<K, V>>(initialListSize);
this.size = 0;
}
/**
* Converts the key into an integer.
*
* @param h
* hash to get index of.
* @return Integer which represents the key.
*/
private int indexOf(int h) {
return h & (array.length-1);
}
/**
* {@inheritDoc}
*/
@Override
public java.util.Map<K,V> toMap() {
return (new JavaCompatibleHashMap<K,V>(this));
}
/**
* {@inheritDoc}
*/
@Override
public boolean validate() {
java.util.Set<K> keys = new java.util.HashSet<K>();
for (List<Pair<K, V>> list : array) {
for (Pair<K, V> pair : list) {
K k = pair.key;
V v = pair.value;
if (k==null || v==null) return false;
if (keys.contains(k)) return false;
keys.add(k);
}
}
return (keys.size()==size());
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int key = 0; key < array.length; key++) {
List<Pair<K, V>> list = array[key];
for (int item = 0; item < list.size(); item++) {
Pair<K, V> p = list.get(item);
V value = p.value;
if (value != null) builder.append(key).append("=").append(value).append(", ");
}
}
return builder.toString();
}
private static class JavaCompatibleHashMap<K,V> extends java.util.AbstractMap<K,V> {
private ChainingHashMap<K,V> map = null;
protected JavaCompatibleHashMap(ChainingHashMap<K,V> map) {
this.map = map;
}
/**
* {@inheritDoc}
*/
@Override
public V put(K key, V value) {
return map.put(key, value);
}
/**
* {@inheritDoc}
*/
@Override
public V remove(Object key) {
return map.remove((K)key);
}
/**
* {@inheritDoc}
*/
@Override
public boolean containsKey(Object key) {
return map.contains((K)key);
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
map.clear();
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return map.size();
}
/**
* {@inheritDoc}
*/
@Override
public java.util.Set<java.util.Map.Entry<K, V>> entrySet() {
java.util.Set<java.util.Map.Entry<K, V>> set = new java.util.HashSet<java.util.Map.Entry<K, V>>() {
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
public java.util.Iterator<java.util.Map.Entry<K, V>> iterator() {
return (new JavaCompatibleIteratorWrapper<K,V>(map,super.iterator()));
}
};
for (List<Pair<K, V>> list : map.array) {
for (Pair<K, V> p : list) {
java.util.Map.Entry<K, V> entry = new JavaCompatibleMapEntry<K, V>(p.key, p.value);
set.add(entry);
}
}
return set;
}
}
}
private static class ProbingHashMap<K, V> extends HashMap<K, V> {
private int hashingKey = -1;
private float loadFactor = 0.6f;
private int minimumSize = 1024;
private Pair<K, V>[] array = null;
private int size = 0;
/**
* Create a hash map with K as the hash.
*
* @param size
* to use for the hash.
*/
public ProbingHashMap(int size) {
initializeMap(size);
}
/**
* Create a hash map with the default hashing key.
*/
public ProbingHashMap() {
initializeMap(minimumSize);
}
/**
* {@inheritDoc}
*/
@Override
public V put(K key, V value) {
return put(new Pair<K,V>(key,value));
}
private V put(Pair<K,V> newPair) {
V prev = null;
int index = indexOf(newPair.key);
// Check initial position
Pair<K, V> pair = array[index];
if (pair == null) {
array[index] = newPair;
size++;
// If size is greater than threshold
int maxSize = (int)(loadFactor*array.length);
if (size >= maxSize)
increase();
return prev;
}
if (pair.key.equals(newPair.key)) {
prev = pair.value;
pair.value = newPair.value;
return prev;
}
// Probing until we get back to the starting index
int start = getNextIndex(index);
while (start != index) {
pair = array[start];
if (pair == null) {
array[start] = newPair;
size++;
// If size is greater than threshold
int maxSize = (int)(loadFactor*array.length);
if (size >= maxSize)
increase();
return prev;
}
if (pair.key.equals(newPair.key)) {
prev = pair.value;
pair.value = newPair.value;
return prev;
}
start = getNextIndex(start);
}
// We should never get here.
return null;
}
/**
* {@inheritDoc}
*/
@Override
public V get(K key) {
int index = indexOf(key);
Pair<K, V> pair = array[index];
// Check initial position
if (pair == null)
return null;
if (pair.key.equals(key))
return pair.value;
// Probing until we get back to the starting index
int start = getNextIndex(index);
while (start != index) {
pair = array[start];
if (pair == null)
return null;
if (pair.key.equals(key))
return pair.value;
start = getNextIndex(start);
}
// If we get here, probing failed.
return null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(K key) {
return (get(key)!=null);
}
/**
* {@inheritDoc}
*/
@Override
public V remove(K key) {
int index = indexOf(key);
Pair<K, V> prev = null;
// Check initial position
Pair<K, V> pair = array[index];
if (pair != null && pair.key.equals(key)) {
prev = array[index];
array[index] = null;
size--;
int loadFactored = (int)(size/loadFactor);
int smallerSize = getSmallerSize(array.length);
if (loadFactored < smallerSize && smallerSize > minimumSize)
reduce();
return prev.value;
}
// Probing until we get back to the starting index
int start = getNextIndex(index);
while (start != index) {
pair = array[start];
if (pair != null && pair.key.equals(key)) {
prev = array[start];
array[start] = null;
size--;
int loadFactored = (int)(size/loadFactor);
int smallerSize = getSmallerSize(array.length);
if (loadFactored < smallerSize && smallerSize > minimumSize)
reduce();
return prev.value;
}
start = getNextIndex(start);
}
// If we get here, probing failed.
return null;
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
for (int i=0; i<array.length; i++)
array[i] = null;
size = 0;
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return size;
}
private void initializeMap(int current) {
int length = getLargerSize(current);
array = new Pair[length];
size = 0;
hashingKey = length;
}
private void increase() {
// Save old data
Pair<K,V>[] temp = this.array;
// Calculate new size and assign
int length = getLargerSize(array.length);
//System.out.println("increase from "+array.length+" to "+length);
initializeMap(length);
// Re-hash old data
for (Pair<K,V> p : temp) {
if (p != null)
this.put(p);
}
}
private void reduce() {
// Save old data
Pair<K,V>[] temp = this.array;
// Calculate new size and check minimum
int length = getSmallerSize(array.length);
//System.out.println("reduce from "+array.length+" to "+length);
initializeMap(length);
// Re-hash old data
for (Pair<K,V> p : temp) {
if (p != null)
this.put(p);
}
}
/**
* Doubles the input. e.g. 16->32
*/
private static final int getLargerSize(int input) {
return input<<1;
}
/**
* Returns one fourth of the input. e.g. 16->8->4
*/
private static final int getSmallerSize(int input) {
return input>>1>>1;
}
/**
* Returns the next index in the probing sequence, at this point it's linear
*/
private int getNextIndex(int input) {
int i = input+1;
if (i >= array.length)
i = 0;
return i;
}
/**
* The hashing function. Converts the key into an integer.
*
* @param key
* to create a hash for.
* @return Integer which represents the key.
*/
private int indexOf(K key) {
int k = Math.abs(key.hashCode()) % hashingKey;
if (k >= array.length)
k = k - ((k / array.length) * array.length);
return k;
}
/**
* {@inheritDoc}
*/
@Override
public java.util.Map<K,V> toMap() {
return (new JavaCompatibleHashMap<K,V>(this));
}
/**
* {@inheritDoc}
*/
@Override
public boolean validate() {
java.util.Set<K> keys = new java.util.HashSet<K>();
for (Pair<K, V> pair : array) {
if (pair == null)
continue;
K k = pair.key;
V v = pair.value;
if (k==null || v==null)
return false;
if (keys.contains(k))
return false;
keys.add(k);
}
return (keys.size()==size());
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int key = 0; key < array.length; key++) {
Pair<K, V> p = array[key];
if (p == null)
continue;
V value = p.value;
if (value != null)
builder.append(key).append("=").append(value).append(", ");
}
return builder.toString();
}
private static class JavaCompatibleHashMap<K,V> extends java.util.AbstractMap<K,V> {
private ProbingHashMap<K,V> map = null;
protected JavaCompatibleHashMap(ProbingHashMap<K,V> map) {
this.map = map;
}
/**
* {@inheritDoc}
*/
@Override
public V put(K key, V value) {
return map.put(key, value);
}
/**
* {@inheritDoc}
*/
@Override
public V remove(Object key) {
return map.remove((K)key);
}
/**
* {@inheritDoc}
*/
@Override
public boolean containsKey(Object key) {
return map.contains((K)key);
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
map.clear();
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return map.size();
}
/**
* {@inheritDoc}
*/
@Override
public java.util.Set<java.util.Map.Entry<K, V>> entrySet() {
java.util.Set<java.util.Map.Entry<K, V>> set = new java.util.HashSet<java.util.Map.Entry<K, V>>() {
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
public java.util.Iterator<java.util.Map.Entry<K, V>> iterator() {
return (new JavaCompatibleIteratorWrapper<K,V>(map,super.iterator()));
}
};
for (Pair<K, V> p : map.array) {
if (p==null)
continue;
java.util.Map.Entry<K, V> entry = new JavaCompatibleMapEntry<K, V>(p.key, p.value);
set.add(entry);
}
return set;
}
}
}
/**
* Create a hash map with K as the hashing key.
*
* @param type
* type of hashing to use.
* @param size
* initialize size.
*/
public HashMap(Type type, int size) {
if (type == Type.CHAINING) {
delegateMap = new ChainingHashMap<K,V>(size);
} else if (type == Type.PROBING) {
delegateMap = new ProbingHashMap<K,V>(size);
}
}
/**
* Create a hash map with the default hashing key.
*
* @param type
* type of hashing to use.
*/
public HashMap(Type type) {
if (type == Type.CHAINING) {
delegateMap = new ChainingHashMap<K,V>();
} else if (type == Type.PROBING) {
delegateMap = new ProbingHashMap<K,V>();
}
}
private HashMap() { }
/**
* {@inheritDoc}
*/
@Override
public V put(K key, V value) {
return delegateMap.put(key, value);
}
/**
* {@inheritDoc}
*/
@Override
public V get(K key) {
return delegateMap.get(key);
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(K key) {
return (get(key)!=null);
}
/**
* {@inheritDoc}
*/
@Override
public V remove(K key) {
return delegateMap.remove(key);
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
delegateMap.clear();
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return delegateMap.size();
}
/**
* {@inheritDoc}
*/
@Override
public java.util.Map<K,V> toMap() {
return delegateMap.toMap();
}
/**
* {@inheritDoc}
*/
@Override
public boolean validate() {
return delegateMap.validate();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return delegateMap.toString();
}
private static final class Pair<K, V> {
private K key = null;
private V value = null;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return 31 * (this.key.hashCode());
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (!(obj instanceof Pair))
return false;
Pair<K, V> pair = (Pair<K, V>) obj;
return key.equals(pair.key);
}
}
private static class JavaCompatibleIteratorWrapper<K,V> implements java.util.Iterator<java.util.Map.Entry<K, V>> {
private HashMap<K,V> map = null;
private java.util.Iterator<java.util.Map.Entry<K, V>> iter = null;
private java.util.Map.Entry<K, V> lastEntry = null;
public JavaCompatibleIteratorWrapper(HashMap<K,V> map, java.util.Iterator<java.util.Map.Entry<K, V>> iter) {
this.map = map;
this.iter = iter;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
if (iter==null)
return false;
return iter.hasNext();
}
/**
* {@inheritDoc}
*/
@Override
public java.util.Map.Entry<K, V> next() {
if (iter==null)
return null;
lastEntry = iter.next();
return lastEntry;
}
/**
* {@inheritDoc}
*/
@Override
public void remove() {
if (iter==null || lastEntry==null)
return;
map.remove(lastEntry.getKey());
iter.remove();
}
}
private static class JavaCompatibleMapEntry<K,V> extends java.util.AbstractMap.SimpleEntry<K,V> {
private static final long serialVersionUID = 3282082818647198608L;
public JavaCompatibleMapEntry(K key, V value) {
super(key, value);
}
}
}