Search code examples
javaarrayslistvariadic-functions

Arrays.asList() not working as it should?


I have a float[] and i would like to get a list with the same elements. I could do the ugly thing of adding them one by one but i wanted to use the Arrays.asList method. There is a problem though. This works:

List<Integer> list = Arrays.asList(1,2,3,4,5);

But this does not.

int[] ints = new int[] {1,2,3,4,5};
List<Integer> list = Arrays.asList(ints);

The asList method accepts a varargs parameter which to the extends of my knowledge is a "shorthand" for an array.

Questions:

  • Why does the second piece of code returns a List<int[]> but not List<int>.

  • Is there a way to correct it?

  • Why doesn't autoboxing work here; i.e. int[] to Integer[]?


Solution

  • How about this?

    Integer[] ints = new Integer[] {1,2,3,4,5};
    List<Integer> list = Arrays.asList(ints);