Explain Codes LogoExplain Codes Logo

How to create a sub array from another array in Java?

java
array-copying
java-8-streams
legacy-java
Nikita BarsukovbyNikita Barsukov·Nov 21, 2024
TLDR

To create a subarray in Java, employ Arrays.copyOfRange. It extracts a particular section of an array, from the start to end-1 indices:

int[] subArray = Arrays.copyOfRange(originalArray, start, end);

Consider that Arrays.copyOfRange is available for JDK 1.5 and later. Note that indexes should fit within the array boundaries to avoid ArrayIndexOutOfBoundsException mishaps.

Extracting subarray for JDK <= 1.5

For legacy Java versions, System.arraycopy() proves an optimal alternative. Though it is low-level, it offers remarkable performance for large arrays or performance-critical applications:

int[] destination = new int[length]; System.arraycopy(sourceArray, start, destination, 0, length);

Ensure to correctly size the destination array before the copy process. Also, note that ArrayIndexOutOfBoundsException is no joke here too. 😼 Remember, this method can be optimized by JIT compilers - a smart move for speed seekers.

Leveraging Java 8 streams methodology

With Java 8, Streams provides an elegant approach for a range of array manipulations. Apply IntStream.range() for advanced manipulations like filtering, mapping:

int[] filteredSubArray = IntStream.range(start, end) .filter(i -> originalArray[i] % 2 == 0) // Show me the even ones! .map(i -> originalArray[i]) // Go fetch 'em! .toArray();

For non-integer arrays, adapt this method with alternatives like .mapToObj(i -> originalArray[i]).

Handling the oldies (JDK <= 1.5)

Stuck with a legacy project or require a more generic solution? Wave hello to your new friend: System.arraycopy(). It's like a classic antique jar - been around forever and works just fine! 🦖

Unleashing power with Apache

Apache Commons Lang fan? For you, ArrayUtils.subarray() offers simplicity of a beach vacation. Trust me, it doesn't get easier:

int[] subArray = ArrayUtils.subarray(originalArray, start, end);

Remember, this library isn't the standard Java coffee, so make sure to brew it into your project.

Troubleshooting: The walk of fame

Things messy? Here are some potential solutions to save your day:

  • Correct import statements are like your house keys. They'll get you in.
  • Your source and destination arrays are proper gremlins. They must be initialized correctly.
  • The index is the master. It must fit within the boundaries.