Arrays.asList() not working as it should?

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.

Leave a Comment