Get only part of an Array in Java?

Learn get only part of an array in java? with practical examples, diagrams, and best practices. Covers java, arrays development techniques with visual explanations.

How to Extract a Sub-Array from an Array in Java

Hero image for Get only part of an Array in Java?

Learn various methods to get a specific portion of an array in Java, covering primitive types and objects, with practical code examples and performance considerations.

Working with arrays is a fundamental task in Java programming. Often, you don't need the entire array but only a specific segment of it. This article explores several common and efficient ways to extract a sub-array from an existing array in Java, catering to both primitive types and object arrays. We'll cover methods using System.arraycopy(), Arrays.copyOfRange(), and manual iteration, discussing their use cases and performance implications.

Understanding Array Slicing Requirements

Before diving into the implementation, it's crucial to understand what 'getting a part of an array' entails. You typically need to specify a starting index and an ending index (or a length) to define the segment you wish to extract. The result will be a new array containing only the elements from the original array within the specified range. It's important to note that Java arrays have a fixed size, so you cannot simply 'resize' an existing array to a smaller portion; you must create a new one.

flowchart TD
    A[Original Array] --> B{Define Start Index}
    B --> C{Define End Index (or Length)}
    C --> D[Create New Array]
    D --> E[Copy Elements from Original to New]
    E --> F[Return New Sub-Array]

Conceptual flow for extracting a sub-array

Method 1: Using System.arraycopy()

The System.arraycopy() method is a native, low-level utility for copying a portion of an array from a source array to a destination array. It's highly optimized and often the fastest option for copying primitive arrays. However, it requires you to manually create the destination array first.

public static int[] getSubArrayWithArrayCopy(int[] originalArray, int startIndex, int length) {
    if (originalArray == null || startIndex < 0 || length < 0 || startIndex + length > originalArray.length) {
        throw new IllegalArgumentException("Invalid input parameters.");
    }
    int[] subArray = new int[length];
    System.arraycopy(originalArray, startIndex, subArray, 0, length);
    return subArray;
}

// Example usage:
int[] original = {10, 20, 30, 40, 50, 60};
int[] sub = getSubArrayWithArrayCopy(original, 2, 3); // Gets {30, 40, 50}
System.out.println(java.util.Arrays.toString(sub));

Extracting a sub-array using System.arraycopy()

Method 2: Using Arrays.copyOfRange()

The java.util.Arrays.copyOfRange() method is a convenient and commonly used way to get a sub-array. It handles the creation of the new array and the copying of elements in a single call. This method is overloaded for all primitive types and for object arrays.

import java.util.Arrays;

public static <T> T[] getSubArrayWithCopyOfRange(T[] originalArray, int startIndex, int endIndex) {
    if (originalArray == null || startIndex < 0 || endIndex > originalArray.length || startIndex > endIndex) {
        throw new IllegalArgumentException("Invalid input parameters.");
    }
    return Arrays.copyOfRange(originalArray, startIndex, endIndex);
}

// Example usage for object array:
String[] originalStrings = {"apple", "banana", "cherry", "date", "elderberry"};
String[] subStrings = getSubArrayWithCopyOfRange(originalStrings, 1, 4); // Gets {"banana", "cherry", "date"}
System.out.println(java.util.Arrays.toString(subStrings));

// Example usage for primitive array:
int[] originalInts = {1, 2, 3, 4, 5};
int[] subInts = Arrays.copyOfRange(originalInts, 0, 3); // Gets {1, 2, 3}
System.out.println(java.util.Arrays.toString(subInts));

Extracting a sub-array using Arrays.copyOfRange() for objects and primitives

Method 3: Manual Iteration (Looping)

While less concise than the built-in methods, manually iterating through the original array and copying elements to a new array provides the most control. This approach can be useful if you need to perform additional logic during the copy process or if you're working in environments where System.arraycopy() or Arrays.copyOfRange() are not available (though rare in standard Java).

public static double[] getSubArrayManually(double[] originalArray, int startIndex, int length) {
    if (originalArray == null || startIndex < 0 || length < 0 || startIndex + length > originalArray.length) {
        throw new IllegalArgumentException("Invalid input parameters.");
    }
    double[] subArray = new double[length];
    for (int i = 0; i < length; i++) {
        subArray[i] = originalArray[startIndex + i];
    }
    return subArray;
}

// Example usage:
double[] originalDoubles = {1.1, 2.2, 3.3, 4.4, 5.5};
double[] subDoubles = getSubArrayManually(originalDoubles, 1, 3); // Gets {2.2, 3.3, 4.4}
System.out.println(java.util.Arrays.toString(subDoubles));

Extracting a sub-array using a manual loop

Performance Considerations

For most applications, the performance difference between System.arraycopy() and Arrays.copyOfRange() (which internally uses System.arraycopy()) will be negligible. Both are highly optimized native methods. Manual looping, while flexible, is generally slower for large arrays due to the overhead of Java bytecode execution compared to native code. When performance is critical for very large arrays, System.arraycopy() is often the preferred choice.