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 =
This is how I would personally solve it. The reason behind creating the parametrized method is to allow any array to be sorted... not just your integers.
I hope you glean something from it.
@Test
public void reverseTest(){
Integer[] ints = { 1, 2, 3, 4 };
Integer[] reversedInts = reverse(ints);
assert ints[0].equals(reversedInts[3]);
assert ints[1].equals(reversedInts[2]);
assert ints[2].equals(reversedInts[1]);
assert ints[3].equals(reversedInts[0]);
reverseInPlace(reversedInts);
assert ints[0].equals(reversedInts[0]);
}
@SuppressWarnings("unchecked")
private static T[] reverse(T[] array) {
if (array == null) {
return (T[]) new ArrayList().toArray();
}
List copyOfArray = Arrays.asList(Arrays.copyOf(array, array.length));
Collections.reverse(copyOfArray);
return copyOfArray.toArray(array);
}
private static T[] reverseInPlace(T[] array) {
if(array == null) {
// didn't want two unchecked suppressions
return reverse(array);
}
Collections.reverse(Arrays.asList(array));
return array;
}