All lessons

HashMaps

8 min · Java

Look up values by key with HashMap — Java's dictionary.

Java · HashMaps0/5 cleared

Enemy 1 of 5

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.

You
Syntax Skeleton

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 10