forked from sam-tripathi/Defeat-JAVA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMap Implementation
More file actions
85 lines (77 loc) · 1.67 KB
/
HashMap Implementation
File metadata and controls
85 lines (77 loc) · 1.67 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
import java.util.ArrayList;
// This is MapNode class
public class MapNode<K, V> {
K key;
V value;
MapNode<K, V> next;
public MapNode(K key, V value) {
this.key = key;
this.value = value;
}
}
// Hashmap functions implementation
public class Map <K, V> {
ArrayList<MapNode<K, V>> buckets;
int size;
int numBuckets;
public Map() {
numBuckets = 5;
buckets = new ArrayList<>();
for (int i = 0; i < numBuckets; i++) {
buckets.add(null);
}
}
private int getBucketIndex(K key) {
int hashCode = key.hashCode();
return hashCode % numBuckets;
}
public int size() {
return size;
}
public V removeKey(K key) {
int bucketIndex = getBucketIndex(key);
MapNode<K, V> head = buckets.get(bucketIndex);
MapNode<K, V> prev = null;
while (head != null) {
if (head.key.equals(key)) {
size--;
if (prev == null) {
buckets.set(bucketIndex, head.next);
} else {
prev.next = head.next;
}
return head.value;
}
prev = head;
head = head.next;
}
return null;
}
public V getValue(K key) {
int bucketIndex = getBucketIndex(key);
MapNode<K, V> head = buckets.get(bucketIndex);
while (head != null) {
if (head.key.equals(key)) {
return head.value;
}
head = head.next;
}
return null;
}
public void insert(K key, V value) {
int bucketIndex = getBucketIndex(key);
MapNode<K, V> head = buckets.get(bucketIndex);
while (head != null) {
if (head.key.equals(key)) {
head.value = value;
return;
}
head = head.next;
}
head = buckets.get(bucketIndex);
MapNode<K, V> newElementNode = new MapNode<K, V>(key , value);
size++;
newElementNode.next = head;
buckets.set(bucketIndex, newElementNode);
}
}