4

I have an array of Strings and I'm looking to be able to do something along the lines of

String[] arrayOfStrings = {"this", "is", "an", "array", "of", "strings"};
List<String> listOfStrings = new ArrayList<String>( arrayOfStrings );

or

List<String> listOfStrings = new ArrayList<String>();
listOfStrings.addAll( arrayOfStrings );

I know I can do both of these if my strings are already in a collection, and also that I can iterate through the array and add them individually, but that one's a little bit messy.

Is there any way to initialise a List (or any collection for that matter) with an array?

0

5 Answers 5

10

You can use Arrays.asList method, which takes a var-args, and returns a fixed-size List backed by an array. So, you can't add any element to this list. Further, any modification done to the elements of the List will be reflected back in the array.

String[] arrayOfStrings = {"this", "is", "an", "array", "of", "strings"};
List<String> list = Arrays.asList(arrayOfStrings);

or: -

List<String> list = Arrays.asList("this", "is", "an", "array", "of", "strings");

If you want to increase the size of this list, you would have to pass it in ArrayList constructor.

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

2 Comments

Is the list unmodifiable?You mean you can not add elements.The list contents are modifiable
@Cratylus. Yeah, I mean we cannot add any element in that. I'll update the answer to remove confusion.
3

You could use Arrays.asList() static method.

For example:

String[] arrayOfStrings = {"this", "is", "an", "array", "of", "strings"};
List<String> list = Arrays.asList(arrayOfStrings);

Note, that you create a fixed-size list "backed up by array" in such a way. If you want to be able to expand it, you'll have to do the following way:

String[] arrayOfStrings = {"this", "is", "an", "array", "of", "strings"};
List<String> list = new ArrayList<String>(Arrays.asList(arrayOfStrings));

2 Comments

Note that it creates a fixed-size list, so if you specifically want an ArrayList you need to do new ArrayList<String>(Arrays.asList("a", "b", "c")).
@RussellZahniser That's a valid note. I'll add this to the answer.
1

You can use asList()

Arrays.asList(T... a) Returns a fixed-size list backed by the specified array.

http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html

Comments

1

This may not fall exactly in your question, but may be worth a consideration.

List<String> list = Arrays.asList("this", "is", "an", "array", "of", "strings");

Comments

0

ArrayList<List<String>> arrayStringMega = new ArrayList<List<String>>(Arrays.asList(Arrays.asList("1","2","3"),Arrays.asList("2","3","4")));

2 Comments

It's just another duplicate answer about Arrays.asList
If you take a closer look. It's been done in one line :)