Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reverse an int array in Java?

I am trying to reverse an int array in Java.

This method does not reverse the array.

for(int i = 0; i < validData.length; i++) {     int temp = validData[i];     validData[i] = validData[validData.length - i - 1];     validData[validData.length - i - 1] = temp; } 

What is wrong with it?

like image 697
MichaelScott Avatar asked Jan 26 '10 06:01

MichaelScott


People also ask

Can you reverse an array in Java?

In Java, the reverse method, which is part of the existing Collections framework, can be used to reverse an array. Let's use it to do the reversal.

Can we reverse int in Java?

There are three ways to reverse a number in Java: Reverse a number using while loop. Reverse a number using for loop. Reverse a number using recursion.


2 Answers

To reverse an int array, you swap items up until you reach the midpoint, like this:

for(int i = 0; i < validData.length / 2; i++) {     int temp = validData[i];     validData[i] = validData[validData.length - i - 1];     validData[validData.length - i - 1] = temp; } 

The way you are doing it, you swap each element twice, so the result is the same as the initial list.

like image 144
3lectrologos Avatar answered Oct 14 '22 03:10

3lectrologos


With Commons.Lang, you could simply use

ArrayUtils.reverse(int[] array) 

Most of the time, it's quicker and more bug-safe to stick with easily available libraries already unit-tested and user-tested when they take care of your problem.

like image 36
Manur Avatar answered Oct 14 '22 05:10

Manur