How to Get Part of an Array or List in Java


Let’s see how we can obtain a part of an array or list (i.e. subarray or sublist).

1. Obtain subarray

1.1. Using Arrays::copyOfRange

We can use Arrays::copyOfRange to copy the contents within a specified range of an array into another array.

int[] src = {0, 1, 2, 3};
int[] dest = Arrays.copyOfRange(src, 0, 1); // {0}
int[] dest = Arrays.copyOfRange(src, 2, 4); // {2, 3}
int[] dest = Arrays.copyOfRange(src, 1, 6); // {1, 2, 3, 0, 0}

The start index is inclusive.

The stop index is exclusive and can be greater than the length of the array. All elements whose index is greater than the length of the array will be null or 0.

1.2. Using System::arrayCopy

We can also use System::arrayCopy to achieve this copy operation.

This method takes quite a few arguments.

System.arraycopy(srcArr, srcPos, destArr, destPos, lengthToCopy);

The following copies a subarray of length 2 that starts at the second index of the src array.

int[] src = {0, 1, 2, 3};
int[] dest = new int[2];
System.arraycopy(src, 2, dest, 0, 2); // {2, 3}

If the stop index is out of bounds, it will throw an IndexOutOfBoundsException error.

2. Obtain sublist

We can perform a similar operation on lists using List::subList.

List<Integer> src = Arrays.asList(0, 1, 2, 3);
List<Integer> dest = src.subList(0, 1); // {0}
List<Integer> dest = src.subList(2, 4); // {2, 3}

The start index is inclusive while the stop index is exclusive.

If the stop index is out of bounds, it will throw an IndexOutOfBoundsException error.