tags:

views:

1400

answers:

8

This may be a bit of an easy, headesk sort of question, but my first attempt surprisingly completely failed to work. I wanted to take an array of primitive longs and turn it into a list, which I attempted to do like this:

long[] input = someAPI.getSomeLongs();
List<Long> = Arrays.asList(input); //Total failure to even compile!

What's the right way to do this?

+6  A: 

A bit more verbose, but this works:

    List<Long> list = new ArrayList<Long>();
    for (long value : input) {
        list.add(value);
    }

In your example it appears that Arrays.asList() is interpreting the input as list of long[] arrays instead of a list of Longs. A bit surprising, for sure. Autoboxing just doesn't work the way you want it to in this case.

hallidave
+3  A: 

No, there is no automatic conversion from array of primitive type to array of their boxed reference types. You can only do

long[] input = someAPI.getSomeLongs();
List<Long> lst = new ArrayList<Long>();

for(long l : input) lst.add(l);
jpalecek
+2  A: 

If you want similar semantics to Arrays.asList then you'll need to write (or use someone else's) customer implementation of List (probably through AbstractList. It should have much the same implementation as Arrays.asList, only box and unbox values.

Tom Hawtin - tackline
+9  A: 
erickson
I tend to leave out the length specification unless the code is proven to be part of a performance hot spot or the array is expected to be extremely large. I think that leaving out the length makes the code slightly more readable.
hallidave
+10  A: 

Fastest way is using apache commons lang ArrayUtils (JavaDoc)

Long[] objectArray = ArrayUtils.toObject(input);

it also has the reverse API

long[] backToPrimitive = ArrayUtils.toPrimitive(objectArray);
Ehrann Mehdan
A: 

You can use transmorph :

Transmorph transmorph = new Transmorph(new DefaultConverters());
List<Long> = transmorph.convert(new long[] {1,2,3,4}, new TypeReference<List<Long>>() {});

It also works if source is an array of ints for example.

cchabanois
A: 

I'm writing a small library for these problems:

long[] input = someAPI.getSomeLongs();
List<Long> = $(input).toList();

In the case you care check it here.

dfa
+2  A: 
import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;

List<Long> longs = Arrays.asList(ArrayUtils.toObject(new long[] {1,2,3,4}));