Lists And ArrayList

A List is an ordered collection that allows duplicates. ArrayList is the general-purpose resizable implementation used most often.

Declare variables with the List interface when callers need list behavior rather than one implementation. Construct ArrayList when you need a mutable list.

Insert an item

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> shoppingList = new ArrayList<>();
        shoppingList.add("Milk");
        shoppingList.add("Bread");
        shoppingList.add(1, "Eggs");
        shoppingList.set(0, "Oat milk");
        shoppingList.remove("Bread");
        System.out.println(shoppingList.get(1));
        System.out.println(shoppingList.size());
        System.out.println(shoppingList);
    }
}

Output:

Eggs
2
[Oat milk, Eggs]

add(1, ...) inserts a new item at index 1 and shifts Bread to the right. set(0, ...) replaces whatever is at index 0, and remove deletes the first matching value, shrinking the list. get reads one element, while size reports how many the list holds.

List.of creates an unmodifiable list. Wrap it in new ArrayList<>(...) before adding, replacing, or removing elements.

Use set and remove to correct a mutable color list.