- Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathCustomHashMapImpl.java
More file actions
Latest commit
105 lines (89 loc) · 3.01 KB
/
Copy pathCustomHashMapImpl.java
File metadata and controls
105 lines (89 loc) · 3.01 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
packagemaps.customhashmap;
/**
* Implementing hashmap.
* User: rpanjrath
* Date: 9/22/13
* Time: 1:17 PM
*/
publicclassCustomHashMapImpl<K, V> implementsCustomHashMap<K, V> {
privateintDEFAULT_BUCKET_COUNT = 10;
Entry[] entryBuckets;
publicCustomHashMapImpl() {
this.entryBuckets = newEntry[DEFAULT_BUCKET_COUNT];
}
publicCustomHashMapImpl(intsize) {
this.entryBuckets = newEntry[size];
}
@Override
publicvoidput(Kkey, Vvalue) {
Entry<K, V> newEntry = newEntry<K, V>(key, value);
if (key == null) {
thrownewIllegalArgumentException("Key " + key + " cannot be null.");
}
intbucketIndex = findBucketUsingHashFunction(key.hashCode());
// Nothing in the bucket. Its a first entry at that bucket[hashcode(key)]
if (entryBuckets[bucketIndex] == null) {
entryBuckets[bucketIndex] = newEntry;
} else {
Entry<K, V> entry = entryBuckets[bucketIndex];
// If same key but different value, then update the value.
if (entry.getKey().equals(key)) {
entry.setValue(value);
} else {
// Different key but same hashcode.. collision.. add to linkedlist
while (entry.getNext() != null) {
entry = entry.getNext();
}
entry.setNext(newEntry);
}
}
}
@Override
publicVget(Kkey) {
if (key == null) {
thrownewIllegalArgumentException("Key " + key + " cannot be null.");
}
intbucketIndex = findBucketUsingHashFunction(key.hashCode());
Entry<K, V> entry = entryBuckets[bucketIndex];
// Loop through bucket if multiple entries.
// current entry will be found once the inputKey is equal to entryKey
// Collisions: Two different keys have same hashCode. It results that both Entries with respective keys
// are added into same bucket.
while (entry != null && !key.equals(entry.getKey())) {
entry = entry.getNext();
}
returnentry != null ? entry.getValue() : null;
}
// This is the hashFunction which will decide on the bucket.
privateintfindBucketUsingHashFunction(inthashCode) {
returnhashCode % entryBuckets.length;
}
@Override
publicbooleanremove(Kkey) {
returnfalse;
}
privatestaticclassEntry<K, V> {
privateEntry<K, V> next;
privatefinalKkey;
privateVvalue;
publicEntry(Kkey, Vvalue) {
this.key = key;
this.value = value;
}
privateVgetValue() {
returnvalue;
}
privatevoidsetValue(Vvalue) {
this.value = value;
}
privateKgetKey() {
returnkey;
}
privateEntry<K, V> getNext() {
returnnext;
}
privatevoidsetNext(Entry<K, V> next) {
this.next = next;
}
}
}