Explain Codes LogoExplain Codes Logo

Get only part of an Array in Java?

java
array-slicing
java-arrays
performance-optimization
Nikita BarsukovbyNikita Barsukov·Dec 6, 2024
TLDR

No time to lose? Java provides Arrays.copyOfRange for quick subarray extraction:

// "In Java no one can hear you scream," but at least you can slice arrays easily int[] subArray = Arrays.copyOfRange(fullArray, start, end);

Start is the inclusive starting index, while end is the exclusive ending index, meaning the elements are copied up to index = end - 1.

Deep dive into array slicing in Java

Ever thought slicing arrays could be a piece of cake in Java? Well, Arrays.copyOfRange ensures that it is.

Working with copyOfRange parameters

The start and end parameters are crucial. Always remember: Arrays.copyOfRange in Java is like a queue at a bakery -- "the first (inclusive) is served, while the last (exclusive) is left wanting".

Immutability: a good thing

Arrays in Java do not change their length once declared. That's why Arrays.copyOfRange would rather create a new array than change the original. It's a neat freak in its own right.

Speaking of alternatives…

In the java world, there’s often more than one way to bake a cake (or slice an array).

In case we're on the List

If you're dealing with Lists, List.subList should be your buddy. All you need to do is convert the array to a list:

// The Java version of a "convertible" needs no fuel, just an "asList" List<Integer> subList = Arrays.asList(fullArray).subList(start, end);

System.arraycopy: for the Performance Philanthropists

For those seeking performance gains and aren't afraid of a bit of manual coding, the System.arraycopy method is the tool of trade. But beware! With great power comes great responsibility - you'll need to handle source and destination positions:

// Handling both source and dest with the elegance of an air traffic controller System.arraycopy(srcArray, srcPos, destArray, destPos, length);

Measure twice, cut once

Java throws an IndexOutOfBoundsException when you index outside the array bounds. Check those indices before your code throws a fit.

Understanding the different tools for slicing

Your choice of tools depends on the requirements and context of your task.

Slicing a thin piece of array

For small data or when precision is key, Arrays.copyOfRange is always a good bet with its neat syntax and readability.

Operating on the big boys

System.arraycopy works wonders with large array sizes thanks to more efficient memory handling.

When the array wants to be a List

For arrays that are destined to become Lists, consider using List.subList from the get-go.

Dealing with index nuances

When handling array indices, be surely aware of common pitfalls and how to tackle them.

Keeping indices in check

Ensure your indices lie within the array bounds. Otherwise, the Java police (ArrayIndexOutOfBoundsException) will come knocking at your code's door.

Handling beyond-the-end indices

Trying to access beyond the last index? Your code will cry wolf (aka ArrayIndexOutOfBoundsException).

Marrying different versions

Arrays.copyOfRange is available from Java 1.6 onwards. If compatibility is key, check your Java version before setting on a date.

Memory considerations: be frugal

Arrays.copyOfRange may allocate additional memory that System.arraycopy does not. So, the latter is preferable in memory-constrained scenarios.