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?

Andrew Logvinov
  • 21,181
  • 6
  • 52
  • 54

5 Answers5

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));
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
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));
Andrew Logvinov
  • 21,181
  • 6
  • 52
  • 54
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

John Humphreys
  • 37,047
  • 37
  • 155
  • 255
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");
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
0

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