forked from TheAlgorithms/Dart
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashmap_implementation
More file actions
73 lines (64 loc) · 1.68 KB
/
hashmap_implementation
File metadata and controls
73 lines (64 loc) · 1.68 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
import 'package:test/test.dart';
// Internal class to store each key-value pair and its next node
class Entry<K, V> {
final K key;
V value;
Entry<K, V> next;
Entry(this.key, this.value, [this.next]);
}
class HashMap<K, V> {
// Internal list to store the keys and values
List<Entry<K, V>> _table;
HashMap() {
_table = List<Entry<K, V>>.filled(256, null);
}
// Helper function to generate a hash code for a key
int _hashCode(K key) {
return key.hashCode % _table.length;
}
// Insert a new key-value pair into the hash map
void insert(K key, V value) {
final int index = _hashCode(key);
if (_table[index] == null) {
_table[index] = Entry<K, V>(key, value);
} else {
Entry<K, V> entry = _table[index];
while (entry.next != null && entry.key != key) {
entry = entry.next;
}
if (entry.key == key) {
entry.value = value;
} else {
entry.next = Entry<K, V>(key, value);
}
}
}
// Get the value associated with a key in the hash map
V get(K key) {
final int index = _hashCode(key);
if (_table[index] == null) {
return null;
} else {
Entry<K, V> entry = _table[index];
while (entry != null && entry.key != key) {
entry = entry.next;
}
return entry?.value;
}
}
}
void main() {
test('adding a key to a map', () {
HashMap map = HashMap();
expect(map.get(1), null);
map.insert(1, 'Akash');
expect(map.get(1), 'Akash');
});
test('updating a key in a map', () {
HashMap map = HashMap();
map.insert(1, 'Akash');
expect(map.get(1), 'Akash');
map.insert(1, 'IronMan');
expect(map.get(1), 'IronMan');
});
}