How to Create Subarray in Java

Java example of creating subarray from an array, i.e., creating array slice. Learn to use Java 8 Arrays.copyOfRange() method, along with converting the subarray to a List object.

String[] names = {"Alex", "Brian", "Charles", "David"};
 
//Subarray from index '0' (inclusive) to index '2' (exclusive)
String[] partialNames = Arrays.copyOfRange(names, 0, 2);  
  // [Alex, Brian]

// Using Common Lang
String[] partialNames = ArrayUtils.subarray(names, 0, 2);    // [Alex, Brian]
 
//Subarray to List
List<String> namesList = Arrays.asList( Arrays.copyOfRange(names, 2, names.length) ); 
  // [Charles, David]

1. Creating Subarray using Arrays.copyOfRange()

The copyOfRange() method is used to copy the specified range of the specified array into a new array. It takes 3 parameters – original array, initial index and final index to be copied.

The ‘to‘ index parameter can be greater than the index length. No ArrayIndexOutOfBoundsException will be raised in this case.

/**
* @param <T> the class of the objects in the array
* @param original the array from which a range is to be copied
* @param from the initial index of the range to be copied, inclusive
* @param to the final index of the range to be copied, exclusive.
*/
public static <T> T[] copyOfRange(T[] original, int from, int to) {
    return copyOfRange(original, from, to, (Class<? extends T[]>) original.getClass());
}

In the following example, we are creating the subarrays from an array of different lengths. Notice if the new array length is greater than the original array then extra array places are filled with the default value of the data type. In given example, the default value of String type is null so extra array places for filled with null.

String[] names = {"Alex", "Brian", "Charles", "David"};			

//Copy till second name from with index '0'
String[] partialNames = Arrays.copyOfRange(names, 0, 2);		// [Alex, Brian]

//Copy all names from with index '2'
String[] endNames = Arrays.copyOfRange(names, 2, names.length);	// [Charles, David]

//Copy last 8 names start with index '2'
//No ArrayIndexOutOfBoundsException error
String[] moreNames = Arrays.copyOfRange(names, 2, 10);   // [Charles, David, null, null, null, null, null, null]

2. Using Common Lang’s ArrayUtils.subarray()

The ArrayUtils.subarray() method returns an array containing the elements of the given array between the start index inclusive and the end index exclusive.

This method is a lot more flexible in handling the otherwise error cases. For example:

  • The method returns null if the given array is null.
  • The start index value will be changed to zero if the start index is less than zero.
  • The method returns an empty array in the following scenarios:
    • The start index is greater than the length of the array.
    • The end index is less than the start index.
  • The end index value will be changed to the length of the array, if the end index is greater than the length of the array.

Add the latest version of Apache Common Lang from the Maven repository.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

The following is an example of using the ArrayUtils.subarray() method.

String[] names = {"Alex", "Brian", "Charles", "David"};

String[] partialNames = ArrayUtils.subarray(names, 0, 2);		// [Alex, Brian]

3. Converting Subarray to List

The following Java example demonstrates to create an ArrayList from a subarray. It is done in two steps:

  • Create a subarray from the array with desired items.
  • Convert array to List.
String[] names = {"Alex", "Brian", "Charles", "David"};
 
//Array to sublist
List<String> namesList = Arrays.asList( Arrays.copyOfRange(names, 0, 2) );  // [Alex, Brian]

Drop me your questions in the comments section.

Happy Learning !!

Sourcecode Download

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial