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:

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:

Where to get it

Maven Dependency (Download):

Links

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

Leave a Reply