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?
-
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.
-
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);
-
If you want similar semantics to
Arrays.asList
then you'll need to write (or use someone else's) customer implementation ofList
(probably throughAbstractList
. It should have much the same implementation asArrays.asList
, only box and unbox values. -
hallidave and jpalecek have the right idea—iterating over an array—but they don't take advantage of a feature provided by
ArrayList
: since the size of the list is known in this case, you should specify it when you create theArrayList
.List<Long> list = new ArrayList<Long>(input.length); for (long n : input) list.add(n);
This way, no unnecessary arrays are created only to be discarded by the
ArrayList
because they turn out to be too short, and no empty "slots" are wasted becauseArrayList
overestimated its space requirements. Of course, if you continue to add elements to the list, a new backing array will be needed.hallidave : 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. -
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);
-
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.
-
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.
-
import java.util.Arrays; import org.apache.commons.lang.ArrayUtils; List<Long> longs = Arrays.asList(ArrayUtils.toObject(new long[] {1,2,3,4}));
0 comments:
Post a Comment