Explain Codes LogoExplain Codes Logo

How do I reverse an int array in Java?

java
array-manipulation
java-8
performance
Nikita BarsukovbyNikita Barsukov·Nov 6, 2024
TLDR

For quick reversal of an int array in Java, wield the 50% savings power of the two-pointer technique. Start with the first and last items, swap them, and converge in the middle:

// Bring out your inner control freak and swap roles for (int i = 0, j = array.length - 1; i < j; i++, j--) { int temp = array[i]; // Temp gets the boring job of holding things array[i] = array[j]; // i basks in glory as the new j array[j] = temp; // j sulks in the corner reassigned as old i }

Keep executing the loop until the midpoint meetup pushes you out of the party.

Library tricks: One-liners and small trade-offs

When you're tired of manual labour, invoke the power of built-in and external libraries:

Apache Commons Lang

Got Commons Lang in your arsenal? If so, reverse like a boss:

// Magic? More like Array Sorcerer-Utils ArrayUtils.reverse(array);

Standard Java Collections

For the purists, leverage the Java Collections Framework, bookend the array as a list, reverse it and transfigure it back:

// Array to List Transformation: Level 100 spell List<Integer> list = Arrays.asList(ArrayUtils.toObject(array)); // Reverse. No, not your decision to be a programmer! Collections.reverse(list); // List back to Array: The spell is complete! array = ArrayUtils.toPrimitive(list.toArray(new Integer[0]));

But beware, the boxing-unboxing jiggery-pokery might slow you down for massive arrays.

The clone saga: Common missteps

When reversing arrays, beware of the Rogue One. These are frequent issues:

  • Banishing Deja-vu: Reversing the array twice results in a back-to-square-one situation.
  • Loop with caution: A stray pointer can lead to a half-hearted reversal.
  • Edge-case alert: Don't fret about arrays with one or no elements. They're already reversed!

An ode to Java 8

Java 8 with its Stream API, offers to turn your code from a working-class car into a smooth riding limousine:

Flamboyant Streams

// Functional programming enthusiasts, rejoice! int[] reversedArray = IntStream.rangeClosed(1, array.length) .map(i -> array[array.length - i]) .toArray();

Remember, while brevity is appreciated, never sacrifice crystal-clear code and swift execution speed.

Don't skip QA

Testing is the tough love your code needs, and the love it deserves:

Testing Scenarios

  • Do a health check with an even number and an odd number of food items.
  • Throw a food festival (aka massive arrays) and ensure no one collapses (ahem, performance).
  • See how your addon services respond to minimal orders: One or no food items.

Edge Cases

  • Memorable orders (sequences of identical food items) want equal attention.
  • The biggest order your restaurant can handle (memory limit).
  • For nested orders (arrays), you need a different recipe.