HashSet<E> and HashMap<K,V>: Multiple Type Parameters
What you'll learn: How to use generic collections that require two type parameters, like HashMap, to store key-value pairs with full type safety.
Collections Beyond Single Type Parameters
You've seen ArrayList<E> and LinkedList<E> use a single type parameter E for the elements they store. But not all collections are simple lists—some need to track relationships between two types of data.
HashMap: Two Type Parameters Working Together
HashMap<K,V> is a collection that stores key-value pairs, where each key maps to a specific value. It requires two type parameters:
K— the type of the keysV— the type of the values
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
Integer aliceAge = ages.get("Alice"); // returns 30, no casting needed
The type safety works for both types: you can't accidentally put an Integer key or a String value where they don't belong.
HashSet: Still Single Type Parameter
For comparison, HashSet<E> stores a collection of unique elements with just one type parameter:
HashSet<String> uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Alice"); // ignored, already present
The Analogy
Think of HashMap as a phone book: you look up a name (key) to find a phone number (value). Both pieces of information have their own types, and the compiler ensures you don't mix them up.
Key Takeaway: Generic collections like HashMap<K,V> can declare multiple type parameters when they need to track relationships between different types of data, providing compile-time type safety for each parameter independently.