So I was trying to reverse an int[] array with Collections.reverse(). It didnt work out for me. Array was getting printed in the same way.
Example :
int[] arr = {1, 2, 3 ,4};
Collections.reverse(Arrays.asList(arr));
Output after printing array : 1 2 3 4
I kept wondering why is this the case? If I use Integer[] array instead of int[], it would reverse perfectly. Any idea why does this happen?
The method from java.util.Collections class
public static void reverse(List<?> list)
Reverses the order of the elements in the specified list.
Parameters:
list - the list whose elements are to be reversed.
The description above mentioned can be found here.
To the question, as it is clear the method requires list to be passed, and not an array (No matter, primitive or non-primitive or wrapper array)
For example below java source let's name it TestReverse.java
import java.util.*;
public class TestReverse {
public static void main(String[] args) {
final int n = 4;
Integer[] arr = new Integer[n];
for(var i = 0; i < n; i++)
arr[i] = i;
System.out.println("Initially : " + Arrays.toString(arr));
Collections.reverse(arr); // show Complier Error at this point.
System.out.println("Later : " + Arrays.toString(arr));
}
}
When running it viz, javac -Xdiags:verbose TestReverse.java
The above code will generate Compiler error
TestReverse.java:10: error: method reverse in class Collections cannot be applied to given types;
Collections.reverse(arr);
^
required: List<?>
found: Integer[]
reason: argument mismatch; Integer[] cannot be converted to List<?>
1 error
Which is quite obvious as the method expects a List but finds to be an array (in this case Integer Array).
If you still want to use the method and get it reversed then make that array work like a list which would be done via, Arrays.asList(arrayOfAnyType)
Hence, reversing would be : Collections.reverse(Arrays.asList(arr));
Making arr array is reversed.
Here Arrays.asList(arr) will be of time O(1) also Collections.reverse(list) is of time O(1).
Other Alternate way is manually swap elements, without help of any method is (which is also quite popular and old school type) having time complexity as O(n),
for(var i = 0; i < arr.length/2; i++) {
var tmp = arr[i];
arr[i] = arr[arr.length - (i+1)];
arr[arr.length - (i+1)] = tmp;
}