Converting Arrays to Lists in Java 5
I’m trying to write some Java 5 (or 1.5, whatever) code for the first time. This is how I used to convert an array to a List in 1.4:List list = Arrays.asList(intArray);
However, Java 5 gives me an error as Arrays.asList(intArray) actually returns a List<int[]>. That’s right, a list of int arrays with a size of 1 instead of a List<Integer>, List of ints with size intArray.length.
So is this correct? Does Arrays.asList(intArray) no longer work for my needs?
For now I am forced to use the following, unless someone can show me the light:
List<Integer> list = new ArrayList<Integer>();
for (Integer i : intArray) list.add(i);
Update:
j yu has helped me to understand the issue at hand, as I have noted in the comments below. Here is the logic for easier viewing…
Under 1.4, you will receive a compile time error for asList(int[]), but under 1.5 asList(int[]) is acceptable with the varargs implementation. 1.5 accepts the array as an object and creates a List<int[]> instead of the List<Integer> that I had expected through autoboxing.
Try this for yourself:int[] intArray = new int[] { 1, 2, 3, 4, 5, 6 };
System.out.println(Arrays.asList(intArray).size());
Integer[] integerArray = new Integer[] { 1, 2, 3, 4, 5, 6 };
System.out.println(Arrays.asList(integerArray).size());
Your output will be:1
6
Since the asList works very differently with int[] and Integer[].
Maybe this should be a warning in Eclipse? It is confusing for both expert and novice users. Or should this even be the correct approach? Shouldn’t the Arrays.asList(int[]) autobox the int’s into a Integer[] for you?
Or is there still an easier solution for me? Maybe through casting or generics? I stumbled upon this while converting int[] to List during a Topcoder event, after updating my jdk from 1.4 to 1.5
Update #2:
In a normal app, it would be easy for me to import the Apache Lang jar, and use ArrayUtils.toObject(intArray). However I’m trying to do this inside of the Topcoder arena applet, so I can’t include any external jars. That’s why I was looking for an api level solution.