Interview ReadyLesson 1 of 6 in Java CollectionsFree preview

List

A List is an ordered collection that allows duplicates and gives access by index.

ClassBacked byGood at
ArrayListresizable arrayget(i), adding at the end
LinkedListdoubly linked listadding/removing at the ends
List<Integer> marks = new ArrayList<>();
marks.add(70);
marks.add(85);
marks.add(0, 60);            // insert at index 0 -> [60, 70, 85]
marks.set(2, 90);            // replace -> [60, 70, 90]
Collections.sort(marks);
Collections.reverse(marks);
Collections.rotate(marks, 1); // last element moves to the front

The classic trap: remove is overloaded. On a List<Integer>, list.remove(1) removes the element at index 1. To remove the value 1, write list.remove(Integer.valueOf(1)).

Second trap: List.of(...) returns an immutable list. Calling add or remove on it throws UnsupportedOperationException. Wrap it, as in new ArrayList<>(List.of(1, 2, 3)), when you need to change it.

In interviews: say you code to the interface (List<Integer> x = new ArrayList<>()) so the implementation can change later.

Practice

Solve 3 of 4 to complete this lesson.

0/4 solved

Solve 3 more to complete this lesson, or move on and come back later.

Skip to next: Set