← Java from Scratch
Lesson 68 of 88 · 10 XP
List
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
List<E> is an ordered list with indices:
List<String> l = new ArrayList<>();
l.add("a"); // to the end
l.add(0, "b"); // insert at an index — the rest move along
l.get(1) // "a"
l.set(1, "c"); // replace
l.remove(0); // by index
l.remove("c"); // by value (the first occurrence)
l.indexOf("x") // -1 if it isn't there
l.subList(1, 3) // a "window" into the list — from 1 to 3, not including 3
List<Integer> fixed = List.of(1, 2, 3); // immutable: add() throws UnsupportedOperationException
A trap with List<Integer>: l.remove(1) removes the element at index 1, while l.remove(Integer.valueOf(1)) removes
the element with the value 1.
Task. A list editor: the commands add X, insert I X, set I X, del I, find X (prints the index
or -1). A wrong index in any command — print bad index and skip it. At the end, print the list in the format
[a, b].
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.