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?
I think it's a little bit easier to follow the logic of the algorithm if you declare explicit variables to keep track of the indices that you're swapping at each iteration of the loop.
I also think it's more readable to do this in a while loop.
Here is a simple implementation, to reverse array of any type, plus full/partial support.
Here is the corresponding Unit Test
Here is what I've come up with:
java.util.Collections.reverse()
can reversejava.util.List
s andjava.util.Arrays.asList()
returns a list that wraps the the specific array you pass to it, thereforeyourArray
is reversed after the invocation ofCollections.reverse()
.The cost is just the creation of one List-object and no additional libraries are required.
A similar solution has been presented in the answer of Tarik and their commentors, but I think this answer would be more concise and more easily parsable.
Wouldn't doing it this way be much more unlikely for mistakes?