I have the following Java code:
import java.util.Arrays;
import java.util.Collections;
public class Test {
public static void main(String[] args) {
int[] test = {1,2,3,4,5};
Collections.rotate(Arrays.asList(test), -1);
for(int i = 0; i < test.length; i++) { System.out.println(test[i]); }
}
}
I want the array to be rotated, but the output I get is
1
2
3
4
5
Why is this?
And is there an alternative solution?
EDIT:
So this works:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
int[] test = {1,2,3,4,5};
List<Integer> testList = new ArrayList<Integer>();
for(int i = 0; i < test.length; i++) { testList.add(test[i]); }
Collections.rotate(testList, -1);
for(int i = 0; i < test.length; i++) { System.out.println(testList.get(i)); }
}
}
But Arrays.asList is supposed to return a list that when written to, copies the changes to the array. Is there any way to fix this without manually doing the conversion from array to list?
I (think that I) can’t afford to waste that much CPU time and memory to do the conversion.
This is a tricky problem: yes,
asListbacks theListit returns with the array, and changes to theListwill “write-through” to the array. However, due to how varargs ofT...interacts with an array of primitive type in this case, you’re actually creating a list with 1 element!Let’s try something different:
As you see, the varargs with an
int[]doesn’t work the way you intended, and the compiler gives an error.Arrays.asListactually returns a 1-elementList<int[]>instead of a 5-elementList<Integer>.Using
Integer[]instead ofint[]works as expected:More explanation
The full signature of
asListis<T> List<T> Arrays.asList(T... a). Note thatTcan’t beintin this case, for the same reason why you can’t have aList<int>in Java:Tneeds to be a reference type.Consider the following snippet:
What happens here is that each
intis boxed into anInteger, and the varargs mechanism “works” andasListcreates a list of 3 elements. Now consider the following form instead:Now the argument to
asListis anint[].Tcan’t be anint, therefore, theT...varargs mechanism “fails”, andasListonly gets one element, and it’s anint[], instead of theintvalues themselves.Now consider this form:
Now since
Integer[]is aT...,asListgets 3 elements as expected.See also
int[]does not autobox to anInteger[]