List
A sequence with indexes
List<E> stores elements in a defined order and lets you access them by index.
Unlike an array, a list can change size: elements can be added and removed while the program is running.
Duplicate values are allowed.
List<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("SQL");
languages.add("Java");
System.out.println(languages.get(1)); // SQL
Indexes start at zero. The get(index) method reads an element,
and set(index, value) replaces the value at an existing position.
Adding and removing
The add(value) method adds an element to the end of the list.
There is also add(index, value), which inserts an element at a particular position.
After such an insertion, the elements to the right shift to new indexes.
List<String> steps = new ArrayList<>();
steps.add("compile");
steps.add("run");
steps.add(1, "test");
steps.remove("test");
System.out.println(steps);
You can remove either by value or by index. These overloads mean different things, so read the call especially carefully when a list stores numbers.
A ready-made list
If the set of values is known immediately and does not need to change, it is convenient to use
List.of(...).
List<String> roles = List.of("USER", "ADMIN");
System.out.println(roles.getFirst());
System.out.println(roles.getLast());
Such a list cannot be expanded, shortened, or have its elements replaced.
The getFirst() and getLast() methods let you read the first and last list elements explicitly.
List is a good fit.
We will compare its main implementations separately.