76

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

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Savvas Dalkitsis
  • 11,476
  • 16
  • 65
  • 104

12 Answers12

95

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.

cambunctious
  • 8,391
  • 5
  • 34
  • 53
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 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? – Geek Jan 15 '14 at 04:49
  • 8
    @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. – Jon Skeet Jan 15 '14 at 06:46
  • with java 8 you can use stream api: List list = Arrays.stream(new int[]{1,2,3}).boxed().collect(Collectors.toList());, a bit verbose though – marcinj Apr 16 '14 at 18:59
  • 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. – Maarten Bodewes Dec 07 '14 at 14:32
  • Warning: lists returned by `Ints.asList` do not support `add()` or related methods – karl Nov 25 '15 at 22:50
39

How about this?

Integer[] ints = new Integer[] {1,2,3,4,5};
List<Integer> list = Arrays.asList(ints);
JRL
  • 76,767
  • 18
  • 98
  • 146
21

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

ChssPly76
  • 99,456
  • 24
  • 206
  • 195
16

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.

YoYo
  • 9,157
  • 8
  • 57
  • 74
  • 1
    You need to cast the result from `toArray()` since it returns `Object[]` – laertis Feb 18 '18 at 15:32
  • 1
    nope .. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#toArray-- – laertis Feb 19 '18 at 11:09
  • Ok. You are right. Type at that point is `Stream` and not `IntStream`. I have fixed it however by using `toArray(Integer[]::new)` instead. Maybe simply typecasting here would be better? – YoYo Feb 19 '18 at 14:37
  • 1
    This is actually a *different* overloaded `toArray()` implementation (https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#toArray-java.util.function.IntFunction-) that uses a _generator function_ and does the job properly. It's better to avoid typecasting where you can.. – laertis Feb 20 '18 at 10:53
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).

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
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.

Community
  • 1
  • 1
BeeOnRope
  • 60,350
  • 16
  • 207
  • 386
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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
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.

Tom Neyland
  • 6,860
  • 2
  • 36
  • 52
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;
}
Maciek Kreft
  • 882
  • 9
  • 14
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.

Donald Raab
  • 6,458
  • 2
  • 36
  • 44
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.

0

There is a better solution for this starting with Java 9:

List<Integer> list = List.of(null, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8);
Matthias Ronge
  • 9,403
  • 7
  • 47
  • 63