Arraylist Slicing

ArrayList slicing allows you to extract a portion of an ArrayList.

It takes two parameters: the starting index and how many elements must be sliced. It returns a new List containing the extracted portion.

ArrayList.slice returns a List instance.

Sublist Between Specified Indices


In this example, animals.subList(1, 4) skips the first element of the ArrayList - 'cat'.

Afterwards, it takes the rest of the ArrayList until it reaches the 4th element - 'dog', 'fish', and 'turtle'.

Excluding the last couple of elements:


This example takes all elements (starting from index 0) and excludes the last 2 elements specified by colors.size() - 2.

In this case colors has 7 elements. So colors.size() - 2 is the same as 7 - 2 which is 5.

Selecting the last couple of elements:


This is the same as:


Removing Sublist

A sublist inside an ArrayList can be removed.


subList(2, 5) selects the folllowing sublist - [blue, pink, gray]

The clear function removes the elements of the sublist.

After removing the sublist elements, the only left elements are - [red, green, purple, white].

Invalid cases

Invalid cases cause error. Such cases are accessing index outside of the ArrayList bounds.


In this example 15 is outside of the ArrayList bounds.

Another case for index being outside of the ArrayList bounds is using negative indexes such as colors.subList(0, -3);.