Java
Array
Programming
Code Snippet
Data Structures

Get only part of an Array in Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Arrays are a fundamental data structure in Java, used to store a collection of elements, typically of the same data type. However, situations frequently arise in which only a part of an array is required, rather than the entire array. In Java, there are several methods to achieve this, ranging from manual array copying to using utility methods from the standard Java libraries.

Manually Extracting Subarrays

The simplest method to extract a part of an array is by manually creating a new array and copying the relevant elements into it. This can be achieved using a simple loop. Here's a straightforward example:

java
1public class ArraySliceExample {
2    public static int[] sliceArray(int[] input, int start, int end) {
3        // Check for invalid indices
4        if(start < 0 || end > input.length || start > end) {
5            throw new IllegalArgumentException("Invalid start or end indices");
6        }
7
8        int[] result = new int[end - start];
9        for (int i = start; i < end; i++) {
10            result[i - start] = input[i];
11        }
12        return result;
13    }
14
15    public static void main(String[] args) {
16        int[] originalArray = {1, 2, 3, 4, 5, 6};
17        int[] slicedArray = sliceArray(originalArray, 2, 5);
18        for (int element : slicedArray) {
19            System.out.println(element);
20        }
21        // Output: 3, 4, 5
22    }
23}

Using System.arraycopy

Java provides a more efficient method, System.arraycopy, which is a native implementation that can be used to copy arrays faster than a manual loop. Here is how you can use it to get a part of an array:

java
1public class ArrayCopyExample {
2    public static int[] copyArrayPart(int[] source, int from, int to) {
3        int[] result = new int[to - from];
4        System.arraycopy(source, from, result, 0, to - from);
5        return result;
6    }
7
8    public static void main(String[] args) {
9        int[] original = {0, 1, 2, 3, 4, 5};
10        int[] partial = copyArrayPart(original, 1, 4);
11        for (int num : partial) {
12            System.out.println(num);
13        }
14        // Output: 1, 2, 3
15    }
16}

Using Arrays.copyOfRange

Arrays.copyOfRange is another utility provided by Java in the java.util.Arrays package, which simplifies the process of copying subarrays:

java
1import java.util.Arrays;
2
3public class CopyOfRangeExample {
4    public static void main(String[] args) {
5        int[] original = {5, 10, 15, 20, 25, 30};
6        int[] sliced = Arrays.copyOfRange(original, 2, 5);
7
8        for (int value : sliced) {
9            System.out.println(value);
10        }
11        // Output: 15, 20, 25
12    }
13}

Each method has its own advantages. For instance, System.arraycopy is extremely efficient for copying large arrays, whereas Arrays.copyOfRange offers a very readable and concise syntax.

Application Scenarios

Extracting subarrays is commonly needed in tasks such as data processing, where only segments of the data are required, or in algorithms where processing needs to be done on chunks of the input data. Subarrays are also frequently used in matrix operations and image processing, where parts of a larger dataset are handled individually.

Summary Table

MethodDescriptionUsage Example
Manual LoopManually copies elements of the array into a new array.sliceArray(originalArray, 2, 5)
System.arraycopyUses system-level routine for fast array copying.copyArrayPart(original, 1, 4)
Arrays.copyOfRangeHigh-level utility method for copying array parts.Arrays.copyOfRange(original, 2, 5)

Conclusion

In Java, extracting parts of an array can be achieved through several methods, each suitable for different scenarios based on the size of the array and the specific requirements of the application. Knowing how to efficiently manage array data is crucial for optimizing performance and resource usage in Java applications.


Course illustration
Course illustration

All Rights Reserved.