Skip to content

Commit 7cafa41

Browse files
committed
HashMap implementation in Java
1 parent ba0a80a commit 7cafa41

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

Diff for: 16.Hash Map/HashMap.java

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
public class HashMap<Key, Value> {
4+
5+
public class Node<Key, Value> {
6+
Key key;
7+
Value value;
8+
9+
Node<Key, Value> next;
10+
11+
public Node(Key k, Value v) {
12+
this.key = k;
13+
this.value = v;
14+
this.next = null;
15+
}
16+
}
17+
18+
List<Node<Key, Value> > Map;
19+
private int N;
20+
21+
public HashMap(int n) {
22+
N = n;
23+
Map = new ArrayList<Node<Key, Value> >(N + 1);
24+
25+
for (int i = 0; i < n; i++)
26+
Map.add(null);
27+
28+
}
29+
30+
public void put(Key k, Value v) {
31+
int loc = (Math.abs(k.hashCode())) % N;
32+
33+
Node<Key, Value> newNode = new Node<Key, Value>(k, v);
34+
newNode.next = Map.get(loc);
35+
Map.set(loc, newNode);
36+
}
37+
38+
public Value get(Key k) {
39+
int loc = Math.abs(k.hashCode()) % N;
40+
41+
Node<Key, Value> crawl = Map.get(loc);
42+
while (crawl != null) {
43+
if (crawl.key == k)
44+
return crawl.value;
45+
crawl = crawl.next;
46+
}
47+
48+
return null;
49+
}
50+
51+
public boolean contains(Key k) {
52+
int loc = Math.abs(k.hashCode()) % N;
53+
54+
Node<Key, Value> crawl = Map.get(loc);
55+
while (crawl != null) {
56+
if (crawl.key == k)
57+
return true;
58+
crawl = crawl.next;
59+
}
60+
return false;
61+
}
62+
63+
public static void main(String[] args) {
64+
HashMap <String, Integer> Map = new HashMap<>(5);
65+
66+
Map.put("abc", 123);
67+
Map.put("brt", 345);
68+
Map.put("cio", 678);
69+
70+
if (Map.contains("brt") == true)
71+
System.out.println(Map.get("brt"));
72+
else
73+
System.out.println("Key doesn't exists");
74+
75+
if (Map.contains("ger") == true)
76+
System.out.println(Map.get("ger"));
77+
else
78+
System.out.println("Key doesn't exists");
79+
80+
}
81+
}

0 commit comments

Comments
 (0)