-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathourHashMap.java
110 lines (93 loc) · 2.1 KB
/
ourHashMap.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
package dataStructure;
import java.util.ArrayList;
class MapNode<K, V> {
K key;
V value;
MapNode<K, V> next;
public MapNode(K key, V value) {
this.key = key;
this.value = value;
next = null;
}
}
public class ourHashMap<K, V> {
ArrayList<MapNode<K, V>> data;
int tableSize;
int count;
public ourHashMap() {
data = new ArrayList<MapNode<K,V>>();
tableSize = 7;
for(int i = 0; i < tableSize; i++) {
data.add(null);
}
count = 0;
}
public void insert(K key, V value) {
// Search if key is already presnt
int index = key.hashCode() % tableSize;
MapNode<K, V> head = data.get(index);
while(head != null) {
if(head.key.equals(key)) {
head.value = value;
return;
}
head = head.next;
}
// Insert new node
MapNode<K, V> newNode = new MapNode<K, V>(key, value);
head = data.get(index);
newNode.next = head;
head = newNode;
data.set(index, head);
count++;
double loadFactor = (count * 1.0) / tableSize;
if(loadFactor > 0.7) {
rehashing();
}
}
private void rehashing() {
ArrayList<MapNode<K, V>> temp = data;
data = new ArrayList<MapNode<K,V>>();
for(int i = 0; i < 2*temp.size(); i++) {
data.add(null);
}
count = 0;
tableSize *= 2; // Next prime number close to double the previous size
for(MapNode<K, V> head : temp) {
while(head != null) {
insert(head.key, head.value);
head = head.next;
}
}
}
public V search(K key) {
int index = key.hashCode() % tableSize;
MapNode<K, V> head = data.get(index);
while(head != null) {
if(head.key.equals(key)) {
return head.value;
}
head = head.next;
}
return null;
}
public void remove(K key) {
int index = key.hashCode() % tableSize;
MapNode<K, V> head = data.get(index);
MapNode<K, V> prev = null;
while(head != null) {
if(head.key.equals(key)) {
if(prev == null) {
data.set(index, head.next);
}
else {
prev.next = head.next;
}
count--;
return;
}
prev = head;
head = head.next;
}
}
}