5. You want to implement a HashMap from scratch in C# that supports storing string keys and integer values. Which approach correctly handles collisions and allows retrieval of values?
class MyHashMap {
private List>[] buckets;
private int size = 10;
public MyHashMap() {
buckets = new List>[size];
for (int i = 0; i < size; i++) buckets[i] = new List>();
}
private int GetBucketIndex(string key) {
return Math.Abs(key.GetHashCode()) % size;
}
public void Put(string key, int value) {
int index = GetBucketIndex(key);
var bucket = buckets[index];
for (int i = 0; i < bucket.Count; i++) {
if (bucket[i].Key == key) {
bucket[i] = new KeyValuePair(key, value);
return;
}
}
bucket.Add(new KeyValuePair(key, value));
}
public int? Get(string key) {
int index = GetBucketIndex(key);
var bucket = buckets[index];
foreach (var kvp in bucket) {
if (kvp.Key == key) return kvp.Value;
}
return null;
}
}
MyHashMap map = new MyHashMap();
map.Put("apple", 5);
map.Put("banana", 3);
map.Put("apple", 10);
int? val = map.Get("apple");
What is the value of
val after this code runs?