×

java · level 2 · unit 2 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.