ITC120_Maps_Lecture Notes (1)
ITC120_Maps_Lecture Notes (1)
Key Features:
Efficient Lookup:
Maps provide fast retrieval of values when the key is known.
Mutability:
Maps are generally mutable, meaning keys and values can be added,
updated, or removed after creation.
TreeMap (Java):
Based on a red-black tree.
Maintains the keys in sorted order.
LinkedHashMap (Java):
Maintains insertion order or access order.
Combines properties of a hash table and a linked list.
ConcurrentMap (Java):
A thread-safe version of a map for use in concurrent programming.
Operations:
Insertion:
Adding a key-value pair.
Example: map.put(key, value) in Java, or map[key] = value in Python.
Lookup:
Retrieving a value by its key.
Example: map.get(key) in Java, or map[key] in Python.
Deletion:
Removing a key-value pair by its key.
Example: map.remove(key) in Java, or del map[key] in Python.
Traversal:
Iterating over keys, values, or key-value pairs.
Example:
Source Code:
import java.util.HashMap;
System.out.println("\nRetrieving Values:");
retrieveValue(map, "Alice");
retrieveValue(map, "Bob");
retrieveValue(map, "Diana"); // Key that doesn't exist
System.out.println("\nChecking Existence:");
checkExistence(map, "Charlie"); // Key exists
checkExistence(map, "Diana"); // Key doesn't exist
System.out.println("\nUpdating Value:");
updateEntry(map, "Alice", "Senior Developer", capacity);
retrieveValue(map, "Alice");
System.out.println("\nRemoving Entry:");
removeEntry(map, "Bob", capacity);
System.out.println("\nFinal Map Content:");
displayMap(map, capacity);
}
// Add entry to the map and compute hash code & bucket index
private static void addEntry(HashMap<String, String> map, String key,
String value, int capacity) {
map.put(key, value);
int hashCode = key.hashCode();
int bucketIndex = hashCode & (capacity - 1);
System.out.println("Added Key: " + key);
System.out.println(" Value: " + value);
System.out.println(" Hash Code: " + hashCode);
System.out.println(" Bucket Index: " + bucketIndex);
}
hashCode=s[0]×31(n -1)+s[1]×31(n-2)+…+s[n-1]
Where:
s[i] is the i-th character of the string.
n is the length of the string.
31 is the multiplier (chosen because it is a prime number, which
reduces hash collisions).
Code Verification:
Output:
Hash code for 'ABC': 64578