3

I am wondering if there's a one-line way of copying an array to a list than the following:

String array[] = new String[]{"1", "2", "3", "4" } ;

List list = new ArrayList();

for (int i=0; i< array.length; i++){
    list.add(array[i] );
}

Edit: thanks for both informative answers, very helpful :)

3
  • 1
    Please use the generic version of List. Also, List<E> is an interface, so it cannot be instantiated: you may create an ArrayList<E> or a LinkedList<E> instead. Commented Mar 7, 2013 at 21:53
  • Thanks, that's what I had to start with but I changed it to list before I posted the question here by mistake. Commented Mar 7, 2013 at 22:00
  • You still have to add the type parameter, e.g. List<String>. Commented Mar 7, 2013 at 22:27

3 Answers 3

9

Yes there is a one liner, use Arrays.asList(T...a) to convert an array into list and pass it as an argument into the ArrayList overloaded constructor which takes a Collection.

List<String> list = new ArrayList<String>(Arrays.asList(array))
Sign up to request clarification or add additional context in comments.

3 Comments

List<E> is an interface, so you cannot instantiate it. Maybe you meant new ArrayList<String>()?
@GiulioPiancastelli oops. sorted that :)
The new is useful only if you want to modify the list, else the answer of Cratylus is better
6

If you need the array in list format but do not actually need to modify structurally the array you can do: List<String> list = Arrays.asList(array);.
Otherwise the answer of@PremGenError is the one to go for.

1 Comment

+1 for the explanation of the difference between Arrays.asList() and the creation of a new list altogether.
2

The simplest approach is:

List<String> fixedList = Arrays.asList(array);

However this will return a fixed-size list backed by the specified array. This means that an attempt to modify the list (such as list.add("10")) will result in a java.lang.UnsupportedOperationExceptionat run-time - so be careful.

A modifiable list can be constructed based on the fixed-size list:

List<String> modifiableList = new ArrayList<String>(fixedList);

Both steps can be amalgamated into a single line of code, like so:

List<String> list = new ArrayList<String>(Arrays.asList(array));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.