Arrays.asList() not working as it should?
Asked Answered
S

11

77

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

Shanahan answered 23/9, 2009 at 18:48 Comment(1)
Btw: what happened to the float[] array?Anorthosite
S
40

How about this?

Integer[] ints = new Integer[] {1,2,3,4,5};
List<Integer> list = Arrays.asList(ints);
Shipentine answered 23/9, 2009 at 18:52 Comment(6)
Beat me, but it would be better with an explanation also.Moffat
unbelievable... It works with reference but not with primitive types :D thanks a lot. :)Shanahan
Hm but is there an easy way to convert an int[] to Integer[]? The thing is i get my array via a method call and i cannot change it.Shanahan
@Savvas: See https://mcmap.net/q/41739/-how-can-i-convert-int-to-integer-in-java or Jon Skeet's answer here. Libraries like Apache Commons Lang or Guava will be of some help.Richers
Can warning be overcome Type safety: The expression of type List needs unchecked conversion to conform to List<Integer> ?Shakeup
Array.asList works only with Objects? Not Primitive array?Acclaim
H
96

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.

Hispanicism answered 23/9, 2009 at 18:53 Comment(5)
Why does "Autoboxing only happens for a single element, not for arrays of primitives.". What do you think is the reason for this design decision?Hewie
@Geek: Well what would you suggest as an alternative? It would be odd for a double[] to be automatically converted to a Double[] by copying all the elements - such that a cast of a reference type would effectively clone the data, unlike every other operation in Java. If you're suggesting that a Double[] should be able to be backed by a double[] in a "view" sort of way, that has other issues such as how you store null references and again the difference between this and other arrays. I think it was the right decision.Hispanicism
with java 8 you can use stream api: List<Integer> list = Arrays.stream(new int[]{1,2,3}).boxed().collect(Collectors.toList());, a bit verbose thoughAngola
One of these Guava functions that should have been added to Java a long way back. Horrible type juggling with primitive types is unfortunately not going away soon.Anabelle
Warning: lists returned by Ints.asList do not support add() or related methodsCapybara
S
40

How about this?

Integer[] ints = new Integer[] {1,2,3,4,5};
List<Integer> list = Arrays.asList(ints);
Shipentine answered 23/9, 2009 at 18:52 Comment(6)
Beat me, but it would be better with an explanation also.Moffat
unbelievable... It works with reference but not with primitive types :D thanks a lot. :)Shanahan
Hm but is there an easy way to convert an int[] to Integer[]? The thing is i get my array via a method call and i cannot change it.Shanahan
@Savvas: See https://mcmap.net/q/41739/-how-can-i-convert-int-to-integer-in-java or Jon Skeet's answer here. Libraries like Apache Commons Lang or Guava will be of some help.Richers
Can warning be overcome Type safety: The expression of type List needs unchecked conversion to conform to List<Integer> ?Shakeup
Array.asList works only with Objects? Not Primitive array?Acclaim
B
21

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

Biogenesis answered 23/9, 2009 at 18:51 Comment(1)
@mmyers In fact, that's what this question is all about. +1 for ChssPly76Piddle
W
17

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.

Weylin answered 4/6, 2015 at 6:16 Comment(4)
You need to cast the result from toArray() since it returns Object[]Abutting
nope .. docs.oracle.com/javase/8/docs/api/java/util/stream/…Abutting
Ok. You are right. Type at that point is Stream<Integer> and not IntStream. I have fixed it however by using toArray(Integer[]::new) instead. Maybe simply typecasting here would be better?Weylin
This is actually a different overloaded toArray() implementation (docs.oracle.com/javase/8/docs/api/java/util/stream/…) that uses a generator function and does the job properly. It's better to avoid typecasting where you can..Abutting
U
5

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).

Urania answered 23/9, 2009 at 18:57 Comment(0)
M
4

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.

Muumuu answered 24/6, 2016 at 0:15 Comment(0)
M
4

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.

Mobcap answered 22/7, 2018 at 2:1 Comment(0)
K
2

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.

Kurtz answered 23/9, 2009 at 18:55 Comment(0)
B
2

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;
}
Byelorussian answered 27/7, 2010 at 4:24 Comment(0)
M
0

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.

Minnick answered 3/11, 2019 at 0:43 Comment(0)
A
0

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.

Addendum answered 12/2, 2021 at 4:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.