Start learning free

LESSON 113 OF 671 · ARRAYS I

Slicing an ArrayList in Java

Lesson

TL ; DR:

list.subList(i, j) gives the items from index i up to, not including, j. Wrap it in new ArrayList<>(...) to get a new list. The original doesn't change.


List<String> letters = new ArrayList<>(List.of("a", "b", "c", "d", "e"));

List<String> middle = new ArrayList<>(letters.subList(1, 4));
// middle is [b, c, d]

// letters is still [a, b, c, d, e]


Full lesson:

Sometimes you need only part of a list, like the first few items. The subList method gives you that part.

Give it the start index and the end index. The item at the end index is not included. So letters.subList(1, 4) has the items at 1, 2 and 3.

That makes the length easy to see: 4 - 1 = 3 items.

To go to the very end, use the size as the end index:

List<String> tail = new ArrayList<>(letters.subList(3, letters.size()));
// tail is [d, e]

On its own, subList doesn't copy anything. It is a window onto the same items, so changing it changes the original too.

So wrap it in new ArrayList<>(...). That copies the items into a new list of its own. The original list stays as it was.


Your task

runners holds a race's runners, in the order they finished.

Put the first three in a new ArrayList named podium. Put everyone else, from index 3 to the end, in one named rest.

The code below prints both, then the length of runners.

Expected output:

Ana Ben Cleo
Dan Eve
5
STEP 1 OF 2
    Ctrl + Enter to check