HashMaps
8 min · Java
Look up values by key with HashMap: Java's dictionary.
Enemy 1 of 5
A HashMap stores pairs, so you look up a value by a key like a name. This code puts a score under Ada and reads it back. Press Run to see it.
Why this works
An ArrayList is great when order matters and you look things up by numeric position, but a lot of real data is more naturally described by name than by position. A HashMap stores key-value pairs: think of it as Java's version of a phone book: instead of looking something up by "item number 4,281," you look it up directly by a meaningful key, like a player's name.
Import java.util.HashMap to use one. A HashMap needs two generic type parameters instead of one (HashMap<String, Integer> means "keys are Strings, values are Integers"), so both sides of every pair are type-checked, not just the values like with an ArrayList.
put(key, value) stores a pair, and get(key) reads the value back out by its key. Asking for a key that was never put into the map (like scores.get("Grace") before it's ever added) returns null rather than throwing an error immediately, something to watch out for, since using that null value later on can cause a NullPointerException, one of the most common runtime errors in Java.
Rena
Your AI tutor. She walks you through each step.
Asking for help is part of coding. Rena reads your code and gives you a hint. She is free with an account: 20 hints a day.