Imagine you want to store and quickly find phone numbers by name. You have two options: a list of pairs (name, number) or a hash map. Why is a hash map better for this?
Think about how long it takes to find a name in a list versus a hash map.
A hash map uses a special function to jump directly to the data for a given key, making lookups very fast. A list requires checking each item until the key is found, which is slower.
Consider this Rust code that uses a hash map to store fruit counts. What will it print?
use std::collections::HashMap;
fn main() {
let mut fruits = HashMap::new();
fruits.insert("apple", 3);
fruits.insert("banana", 2);
fruits.insert("orange", 5);
if let Some(count) = fruits.get("banana") {
println!("{}", count);
} else {
println!("Not found");
}
}Look at the key used in the get method and the value inserted for that key.
The code inserts 2 for the key "banana" and then retrieves it, printing 2.
Look at this Rust code snippet. What error will it cause?
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("key1", 10);
let value = map["key2"];
println!("{}", value);
}What happens if you try to access a key that does not exist in a hash map using the index syntax?
Using map["key2"] tries to get the value for "key2" but it does not exist, causing a runtime panic.
Which statement best explains how a hash map helps retrieve data quickly?
Think about how the key is transformed to find the value quickly.
A hash map applies a hash function to keys to find the exact place where the value is stored, avoiding searching through all data.
Given this Rust code, what is the printed state of the hash map?
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
map.insert("a", 4);
for (key, value) in &map {
println!("{} -> {}", key, value);
}
}What happens when you insert a value with a key that already exists?
Inserting with the same key updates the value. So "a"'s value changes from 1 to 4. The map contains keys "a", "b", and "c" with their latest values.
