×

java · level 2 · unit 1 · 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

An is a list that grows when you add to it.

An array has a fixed , so you must know how many slots you need before you start. An ArrayList is a list that grows: start it empty, then add as many items as you like. Borrow it with import java.util.ArrayList; at the top.

ArrayList<String> pets = new ArrayList<>(); makes an empty list of strings. The , < and >, say what type of item it keeps. The empty pair after new tells Java to copy the type from the left.

.add("cat") puts an item on the end. .size() gives its size, the number of items right now. .get(0) hands back the item at index 0. Printing a whole list shows every item, like [cat, dog].

import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList<String> pets = new ArrayList<>();
        pets.add("cat");
        pets.add("dog");
        pets.add("hamster");
        System.out.println(pets);
        System.out.println(pets.size());
        System.out.println(pets.get(0));
    }
}

Use .size() for lists, .length() for strings and .length for arrays.