Yesterday, I had some fun with Java again. Since Java 1.5 it has become so natural to mix primitive datatypes with their object based counter parts as Java boxes and unboxes expressions as necessary without the need to make any explicit casts – or so I thought.
Take a look at the code below:
byte[] testBytes1 = {1, 2, 3, 4, 5};
List<Byte> list1 = Arrays.asList(testBytes1);
If you expected that you can create a list of Byte objects from a byte[] array, then you’re sadly mistaken. As Java cannot autobox arrays (which are backed up by a separate type, not equal to the respective primitive elements within), Arrays.asList will not accept testBytes1 since its type is byte[] which is not autoboxed into Byte[]. So above example code is not valid without changes.
It would compile like this:
byte[] testBytes1 = {1, 2, 3, 4, 5};
List<byte[]> list1 = Arrays.asList(testBytes1);
So, now you expect that you will end up with a list of five Byte objects? Wrong again. Look at the expression and its type. The type is still byte[]. So, list1 contains exactly one element, which is an array with five byte literals.
Long story, short answer: before using Arrays.asList loop over a primitive array and copy the elements to an object based array.