×

java · level 2 · unit 1 · lesson 2

  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

Lists can change: swap, squeeze in and items.

.set(1, "pear") swaps the item at index 1 for a new one. .add(0, "kiwi") squeezes an item in at index 0, and every item after it will along one place to make room.

.remove takes an item out. Give it an index, like .remove(0), or the item itself, like .remove("plum"). The items after the gap shift back, so their indexes all drop by one.

Ask for an index the list does not have, and Java stops with an IndexOutOfBoundsException. A list of 3 items has indexes 0, 1 and 2, the same as an array.

import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruit = new ArrayList<>();
        fruit.add("apple");
        fruit.add("banana");
        fruit.add("plum");
        fruit.set(1, "pear");
        fruit.add(0, "kiwi");
        fruit.remove("plum");
        System.out.println(fruit);
    }
}

.set replaces an item, but .add with an index makes the list one longer.