Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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[]?

like image 879
Savvas Dalkitsis Avatar asked Sep 23 '09 18:09

Savvas Dalkitsis


People also ask

What does arrays asList () do?

The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.

How is array asList () different?

asList method returns a type of ArrayList that is different from java. util. ArrayList. The main difference is that the returned ArrayList only wraps an existing array — it doesn't implement the add and remove methods.

Can arrays asList be modified?

Arrays. asList() method returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, it is impossible to add elements to the list or remove elements from it.

How is arrays asList () different than the standard way of initializing list?

How is Arrays. asList() different than the standard way of initialising List? Explanation: List returned by Arrays. asList() is a fixed length list which doesn't allow us to add or remove element from it.


1 Answers

There's no such thing as a List<int> in Java - generics don't support primitives.

Autoboxing only happens for a single element, not for arrays of primitives.

As for how to correct it - there are various libraries with oodles of methods for doing things like this. There's no way round this, and I don't think there's anything to make it easier within the JDK. Some will wrap a primitive array in a list of the wrapper type (so that boxing happens on access), others will iterate through the original array to create an independent copy, boxing as they go. Make sure you know which you're using.

(EDIT: I'd been assuming that the starting point of an int[] was non-negotiable. If you can start with an Integer[] then you're well away :)

Just for one example of a helper library, and to plug Guava a bit, there's com.google.common.primitive.Ints.asList.

like image 141
Jon Skeet Avatar answered Oct 13 '22 20:10

Jon Skeet