Arrays.asList() not working as it should?

JavaArraysListVariadic Functions

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

How about this?

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

Solution 3 - Java

Because java arrays are objects and Arrays.asList() treats your int array as a single argument in the varargs list.

Solution 4 - Java

Enter Java 8, and you can do following to collect in a boxed Array:

Integer[] boxedInts = IntStream.of(ints).boxed().toArray(Integer[]::new);

Or this to collect in a boxed List

List<Integer> boxedInts = IntStream.of(ints).boxed().collect(Collectors.toList());

However, this only works for int[], long[], and double[]. This will not work for byte[].

Note that Arrays.stream(ints) and IntStream.of(ints) are equivalent. So earlier two examples can also be rewritten as:

Integer[] boxedIntArray = Arrays.stream(ints).boxed().toArray(Integer[]::new);
List<Integer> boxedIntList = Arrays.stream(ints).boxed().collect(Collectors.toList());

This last form could be favored as it omits a primitive specific subtype of Stream. However, internally it is still a bunch of overloaded's which in this case still create a IntStream internally.

Solution 5 - Java

The problem is not with Arrays.asList(). The problem is that you expect autoboxing to work on an array - and it doesn't. In the first case, the compiler autoboxes the individual ints before it looks at what they're used for. In the second case, you first put them into an int array (no autoboxing necessary) and then pass that to Arrays.asList() (not autoboxing possible).

Solution 6 - Java

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

While autoboxing will convert an int to an Integer, it will not convert an int[] to an Integer[].

Why not?

The simple (but unsatisfying) answer is because that is what the JLS says. (You can check it if you like.)

The real answer is fundamental to what autoboxing is doing and why it is safe.

When you autobox 1 anywhere in your code, you get the same Integer object. This is not true for all int values (due to the limited size of the Integer autoboxing cache), but if you use equals to compare Integer objects you get the "right" answer.

Basically N == N is always true and new Integer(N).equals(new Integer(N)) is always true. Furthermore, these two things remain true ... assuming that you stick with Pure Java code.

Now consider this:

int[] x = new int[]{1};
int[] y = new int[]{1};

Are these equal? No! x == y is false and x.equals(y) is false! But why? Because:

y[0] = 2;

In other words, two arrays with the same type, size and content are always distinguishable because Java arrays are mutable.

The "promise" of autoboxing is that it is OK to do because the results are indistinguishable1. But, because all arrays are fundamentally distinguishable because of the definition of equals for arrays AND array mutability. So, if autoboxing of arrays of primitive types was permitted, it would undermine the "promise".


1 - ..... provided that you don't use == to test if autoboxed values are equal.

Solution 7 - Java

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 ints, this may pay off, but it's something to be aware of.

Solution 8 - Java

If you pass an int[] to Arrays.asList(), the list created will be List<int[]>, which is not vaild in java, not the correct List<Integer>.

I think you are expecting Arrays.asList() to auto-box your ints, which as you have seen, it won't.

Solution 9 - Java

It's not possible to convert int[] to Integer[], you have to copy values


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

public static List<Integer> asList(int[] a) {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < a.length && list.add(a[i]); i++);
    return list;
}

Solution 10 - Java

Alternatively, you can use IntList as the type and the IntLists factory from Eclipse Collections to create the collection directly from an array of int values. This removes the need for any boxing of int to Integer.

IntList intList1 = IntLists.mutable.with(1,2,3,4,5);
int[] ints = new int[] {1,2,3,4,5};
IntList intList2 = IntLists.mutable.with(ints);
Assert.assertEquals(intList1, intList2);

Eclipse Collections has support for mutable and immutable primitive List as well as Set, Bag, Stack and Map.

Note: I am a committer for Eclipse Collections.

Solution 11 - Java

int is a primitive type. Arrays.asList() accept generic type T which only works on reference types (object types), not on primitives. Since int[] as a whole is an object it can be added as a single element.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSavvas DalkitsisView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaJRLView Answer on Stackoverflow
Solution 3 - JavaChssPly76View Answer on Stackoverflow
Solution 4 - JavaYoYoView Answer on Stackoverflow
Solution 5 - JavaMichael BorgwardtView Answer on Stackoverflow
Solution 6 - JavaStephen CView Answer on Stackoverflow
Solution 7 - JavaBeeOnRopeView Answer on Stackoverflow
Solution 8 - JavaTom NeylandView Answer on Stackoverflow
Solution 9 - JavaMaciek KreftView Answer on Stackoverflow
Solution 10 - JavaDonald RaabView Answer on Stackoverflow
Solution 11 - JavaElias AndualemView Answer on Stackoverflow