Collections Framework 2
Lesson 17 of 20Keys, buckets and no duplicates — put and get your way through HashMap and HashSet in one interactive tour.
Look things up by key
A HashMap maps each key to exactly one value; a HashSet is the same machinery holding keys only — and never a duplicate.
HashMap = dictionary
put(key, value) stores, get(key) looks up — no scanning, the key decides where to look.
Keys are unique
put with an existing key REPLACES its value. One key, one entry, always.
hashCode finds buckets
The key is hashed into a bucket index; equals() settles ties inside the bucket.
HashSet = keys only
add(x) quietly does nothing if x is already present — duplicates simply cannot exist.
Inside one put() call
What map.put("pen", 9) does under the hood, stage by stage.
Scores and a picky set
Tab one: replacing a value under an existing key. Tab two: a HashSet swallowing a duplicate.
1import java.util.HashMap;23public class ScoreDemo {4public static void main(String[] args) {5HashMap<String, Integer> scores = new HashMap<>();6scores.put("Ana", 90);7scores.put("Bo", 85);8scores.put("Ana", 95);9System.out.println(scores.get("Ana"));10System.out.println(scores.size());11}12}
main begins.
Map and set moves
Match each call to its job.
The replacement pen
One key, written twice — what survives?
1import java.util.HashMap;23public class StockDemo {4public static void main(String[] args) {5HashMap<String, Integer> stock = new HashMap<>();6stock.put("pen", 4);7stock.put("pen", 9);8stock.put("bag", 2);9System.out.println(stock.get("pen"));10System.out.println(stock.size());11}12}
Hint: The second put("pen", ...) REPLACES the 4 — the map still holds exactly two entries.
Key takeaways
HashMap gives instant lookup because the key decides where its entry lives.
putting an existing key replaces its value — keys are always unique.
HashSet is a HashMap without the values: unique elements, fast contains.
Printing a map or set shows its contents, but never rely on the order.
Your keys should have good hashCode() and equals() — String and Integer already do.