phcoding
phcoding

Reputation: 608

Copying an array to a list

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 :)

Upvotes: 3

Views: 361

Answers (3)

paulkore
paulkore

Reputation: 665

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));

Upvotes: 2

Cratylus
Cratylus

Reputation: 54074

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.

Upvotes: 6

PermGenError
PermGenError

Reputation: 46408

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))

Upvotes: 9

Related Questions