Arrays.asList(T... a)
effectively takes a T[]
which will match any array of true objects (subclasses of Object
) as an array. The only thing that won't match like that is an array of primitives, since primitive types do not derive from Object
. So an int[]
is not an Object[]
.
What happens then is that the varags mechanism kicks in and treats it as if you had passed a single object, and creates a single element array of that type. So you pass an int[][]
(here, T
is int[]
) and end up with a 1-element List<int[]>
which is not what you want.
You still have some pretty good options though:
Guava's Int.asList(int[])
Adapter
If your project already uses guava, it's as simple as using the adapter Guava provides: Int.asList(). There is a similar adapter for each primitive type in the associated class, e.g., Booleans
for boolean
, etc.
int foo[] = {1,2,3,4,5};
Iterable<Integer> fooBar = Ints.asList(foo);
for(Integer i : fooBar) {
System.out.println(i);
}
The advantage of this approach is that it creates a thin wrapper around the existing array, so the creation of the wrapper is constant time (doesn't depend on the size of the array), and the storage required is only a small constant amount (less than 100 bytes) in addition to the underlying integer array.
The downside is that accessing each element requires a boxing operation of the underlying int
, and setting requires unboxing. This may result in a large amount of transient memory allocation if you access the list heavily. If you access each object many times on average, it may be better to use an implementation that boxes the objects once and stores them as Integer
. The solution below does that.
Java 8 IntStream
In Java 8, you can use the Arrays.stream(int[])
method to turn an int
array into a Stream
. Depending on your use case, you may be able to use the stream directly, e.g., to do something with each element with forEach(IntConsumer)
. In that case, this solution is very fast and doesn't incur any boxing or unboxing at all, and does not create any copy of the underlying array.
Alternately, if you really need a List<Integer>
, you can use stream.boxed().collect(Collectors.toList())
as suggested here. The downside of that approach is that it fully boxes every element in the list, which might increase its memory footprint by nearly an order of magnitude, it create a new Object[]
to hold all the boxed elements. If you subsequently use the list heavily and need Integer
objects rather than int
s, this may pay off, but it's something to be aware of.
float[]
array? – Anorthosite