Thoughts are free, who can guess them?
They flee by like nocturnal shadows.
No man can know them, no hunter can shoot them,
with powder and lead: Thoughts are free!
About www.weisserth.net
Tobias Weisserth
Hamburg, Germany
photographer & independent gearhead

Java, arrays, autoboxing and Arrays.asList

Posted by polarapfel on Thu, 06 May 2010 16:54

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.

Trackbacks

Use the following link to trackback from your own site:
http://www.weisserth.net/trackbacks?article_id=18

Comments

Leave a comment

Comments