Imagine you want to store and quickly find phone numbers by name. Which problem does a Hash Map solve better than a List?
Think about how quickly you can find a phone number by name in each data structure.
A Hash Map uses a special function to jump directly to the data by key, making lookup very fast. A List requires checking each item until the key is found, which is slower.
Consider this Java code using a Hash Map. What will be printed?
import java.util.HashMap; public class Main { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("apple", 3); map.put("banana", 2); map.put("apple", 5); System.out.println(map); } }
What happens when you put a value with a key that already exists?
When inserting a key that already exists, the Hash Map updates the value. So 'apple' key's value changes from 3 to 5.
What happens if you try to get a value for a key that does not exist in a Java Hash Map?
import java.util.HashMap; public class Main { public static void main(String[] args) { HashMap<String, String> map = new HashMap<>(); map.put("cat", "meow"); System.out.println(map.get("dog").length()); } }
What does map.get("dog") return if "dog" is not a key?
map.get("dog") returns null because the key is missing. Calling length() on null causes NullPointerException.
What role does hashing play in how a Hash Map works?
Think about how the Hash Map finds where to store or find a key.
Hashing turns keys into numbers (hash codes) that help the Hash Map jump directly to the place where the value is stored, making operations fast.
You need to store many unique user IDs and quickly check if a user exists or add a new user. Which data structure is best?
Consider average time complexity for lookup and insertion.
Hash Map offers average constant time O(1) for lookup and insertion, making it ideal for fast operations with unique keys.
