This may be a bit of an easy, headdesk 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:

Considering that this creates an array of Longs, not a List, it doesn't answer OP's question and gets my downvote. How the heck did this get 56 upvotes and the coveted "check"???
–
user949300Aug 13 '14 at 17:53

2

Because people can easily do Arrays.asList(ArrayUtils.toObject(input)) probably.
–
Eran MedanAug 13 '14 at 21:22

I agree with @user949300. This doesn't answer the question.
–
ovaherenowJun 19 at 19:50

This answer should be updated to provide a complete conversion to a list. However, it is an efficient step towards the solution.
–
Jim JeffersJul 29 at 16:11

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 the ArrayList.

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 because ArrayList overestimated its space requirements. Of course, if you continue to add elements to the list, a new backing array will be needed.

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.
–
hallidaveApr 18 '09 at 16:28

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.

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.

Fantastic! I'm glad my sardonic attitude led to progress instead of just general bad feelings all around :) Really, it's not a good idea to use exceptions except in very unusual conditions. They're surprisingly expensive to create. This new version is much, MUCH faster.
–
Brandon YarbroughOct 17 '12 at 22:42