java · level 2 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A files each value under a .
A list finds things by index. A HashMap finds them by name, like a coat check: hand over your coat, get a ticket, and the ticket gets your coat back. The ticket is the key, and the coat is its value.
HashMap<String, Integer> stock = new HashMap<>(); makes a map with String keys and Integer values. stock.put("apples", 12) files 12 under apples. stock.get("apples") hands it back, and .size() counts the pairs.
Ask for a key that is not there and you get , Java's word for nothing at all.
import java.util.*;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> stock = new HashMap<>();
stock.put("apples", 12);
stock.put("pears", 7);
System.out.println(stock.get("apples"));
System.out.println(stock.size() + " kinds of fruit");
System.out.println(stock.get("mangoes"));
}
} Each key appears only once in a map, but two keys can share the same value.
guess first
Look up a phone number. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.*;
public class Main {
public static void main(String[] args) {
HashMap<String, String> phones = new HashMap<>();
phones.put("Mum", "07700 900123");
phones.put("Gran", "07700 900456");
System.out.println(phones.get("Gran"));
System.out.println(phones.get("gran"));
}
}
your turn
Your turn. Price up a snack.
On line 6, add a snack of your own and its price in pence. On line 7, type the same snack's name, then press run to look it up.
output
press run to see what happens
fix it
The apples went missing. Can you fix it?
output
press run to see what happens
- Java stopped with a
NullPointerExceptionon line 7. What doesgetgive for a key that is not there? - Keys are case-sensitive. The map has apples with a small a, so
"Apples"givesnull, andnullcannot go in anintbox. - Change
"Apples"to"apples"on line 7, then press run.
nailed it
you filed values under keys. :D
- A
HashMapstores pairs: each key leads to one value. .putfiles a value, and.gethands it back.- A missing key gives
null, which means nothing at all.
new words in your collection
- HashMap
- key
- null
This lesson isn’t saved. A free account remembers every lesson you finish.