-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashmap.java
More file actions
88 lines (74 loc) · 2.9 KB
/
Copy pathHashmap.java
File metadata and controls
88 lines (74 loc) · 2.9 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
public class Hashmap {
public static void main(String[] args){
HashMap<String, Integer> map = new HashMap<>();
// 1. Basic put and get
map.put("one", 1);
System.out.println("Get 'one': " + map.get("one")); // Expected: 1
// 2. Put multiple keys
map.put("two", 2);
map.put("three", 3);
System.out.println("Get 'two': " + map.get("two")); // Expected: 2
System.out.println("Get 'three': " + map.get("three")); // Expected: 3
// 3. Update existing key
map.put("two", 22);
System.out.println("Updated 'two': " + map.get("two")); // Expected: 22
// 4. Get non-existent key
System.out.println("Get 'four': " + map.get("four")); // Expected: null
// 5. Keys that could hash to the same index
// (Force a collision by crafting keys with the same hash % size)
map.put("Aa", 100); // "Aa".hashCode() == 2112
map.put("BB", 200); // "BB".hashCode() == 2112 in Java
System.out.println("Collision test - 'Aa': " + map.get("Aa")); // Expected: 100
System.out.println("Collision test - 'BB': " + map.get("BB")); // Expected: 200
// 6. Overwrite after collision
map.put("Aa", 111);
System.out.println("Updated collision key 'Aa': " + map.get("Aa")); // Expected: 111
}
public static class Entry<K, V>{
K key;
V value;
Entry<K, V> next;
Entry(K key, V value){
this.key = key;
this.value = value;
}
}
public static class HashMap<K, V>{
private int size = 20;
private Entry<K, V>[] hashtable;
public HashMap(){
hashtable = new Entry[size];
}
public void put(K key, V value) {
int index = Math.abs(key.hashCode() % size);
Entry<K, V> newEntry = new Entry<>(key, value);
if (hashtable[index] == null) {
hashtable[index] = newEntry;
} else {
Entry<K, V> current = hashtable[index];
while (true) {
if (current.key.equals(key)) {
current.value = value;
return;
}
if (current.next == null) {
current.next = newEntry;
return;
}
current = current.next;
}
}
}
public V get(K key) {
int index = Math.abs(key.hashCode() % size);
Entry<K, V> current = hashtable[index];
while (current != null) {
if (current.key.equals(key)) {
return current.value;
}
current = current.next;
}
return null;
}
}
}