How to create a sub array from another array in Java?
There are a few different ways to create a subarray from another array in Java:
There are a few different ways to create a subarray from another array in Java:
- Using
Arrays.copyOfRange:
import java.util.Arrays;
int[] originalArray = {1, 2, 3, 4, 5};
int[] subArray = Arrays.copyOfRange(originalArray, 1, 4);
// subArray is now {2, 3, 4}This is the most readable and commonly used approach. It handles bounds checking automatically and is generally preferred for simplicity.
- Using
System.arraycopy:
int[] originalArray = {1, 2, 3, 4, 5};
int[] subArray = new int[3];
System.arraycopy(originalArray, 1, subArray, 0, 3);
// subArray is now {2, 3, 4}This is a low-level, highly efficient method often used in performance-critical code. Note that you must pre-allocate the destination array.
- Using a loop:
int[] originalArray = {1, 2, 3, 4, 5};
int[] subArray = new int[3];
for (int i = 0; i < 3; i++) {
subArray[i] = originalArray[i + 1];
}
// subArray is now {2, 3, 4}This manual approach gives full control over the copying process but is more verbose and slower than built-in methods.
- Using
List.subList:
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
int[] originalArray = {1, 2, 3, 4, 5};
List<Integer> originalList = IntStream.of(originalArray).boxed().collect(Collectors.toList());
List<Integer> subList = originalList.subList(1, 4);
// subList is now [2, 3, 4]This method returns a List<Integer> view backed by the original list, not a primitive int[] array. Modifications to the sublist affect the original list. If you need a primitive array, convert it back using subList.stream().mapToInt(Integer::intValue).toArray().
Summary
For most use cases, Arrays.copyOfRange is the best choice due to its readability and safety. Use System.arraycopy for maximum performance in tight loops. The manual loop is rarely needed unless custom logic is required. List.subList is useful when working with collections, but remember it returns a live view, not a new array.