Make Arrays.asList() handle primitive arrays

Naively, I supposed that every varargs parameter in Java could be treated just like a normal array. This is not the case for primitive arrays as I had to learn!

Using the standard library method Arrays.asList(T…) that converts arrays/varargs of objects to java.util.List‘s, an idiomatic code snippet may look like this:

final int[] ints = { 3, 2, 8, 1, 1, 5 };
final List<Integer> list = Arrays.asList(ints);
Collections.sort(list);

However, the Java compiler complains about the second line:

Type mismatch: cannot convert from List<int[]> to List<Integer>

Obviously, the type parameter T is resolved to int[]. Apache Commons-Lang offers helps to resort from this problem: Its ArrayUtils.toObject() method takes a primitive array and converts it to the corresponding object array. The following, modified listing demonstrates this:

final int[] ints = { 3, 2, 8, 1, 1, 5 };
// final List<Integer> list = Arrays.asList(ints);
final Integer[] intObjects = ArrayUtils.toObject(ints);
final List<Integer> list = Arrays.asList(intObjects);
Collections.sort(list);

Where to get it

Maven Dependency (Download):

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

Links

  • [1] Related stackoverflow question
  • [2] Arrays.asList(T…) docu (Java 6)
  • [3] ArrayUtils.toObject() docu (Commons-Lang 2.6)

Leave a Reply