Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to create a list

Short answer

A modifiable list is an ArrayList. You can add and remove elements:

void main() {
    List<String> names = new ArrayList<>();
    names.add("Anna");
    names.add("Oleg");
 
    IO.println(names);
    IO.println(names.size());
}

Output:

[Anna, Oleg]
2

With elements right away

List.of() creates an unmodifiable list — handy for constants and read-only data:

void main() {
    List<String> days = List.of("Mon", "Tue", "Wed");
    IO.println(days.get(1));
}

Output:

Tue

Modifiable with initial elements

Pass List.of() to the ArrayList constructor — you get a modifiable copy:

void main() {
    List<Integer> numbers = new ArrayList<>(List.of(3, 1, 2));
    numbers.add(4);
    numbers.remove(Integer.valueOf(1));
 
    IO.println(numbers);
}

Output:

[3, 2, 4]

The type with var

With var the type is written only on the right:

void main() {
    var prices = new ArrayList<Double>();
    prices.add(9.99);
 
    IO.println(prices);
}

Output:

[9.99]

Common mistake

Modifying a list from List.of(). It is unmodifiable, and any attempt throws:

void main() {
    List<String> days = List.of("Mon", "Tue");
    days.add("Wed");
}

Output:

Exception in thread "main" java.lang.UnsupportedOperationException

Another detail: List.of() does not accept null elements.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.