Initializing ArrayList with array in one line
I have an array String
and I want to do something according to
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 this if my strings are already in the collection, and also that I can loop over the array and add them individually, but this is a little messy.
Is there a way to initialize List
(or any collection for that matter) with an array?
source to share
You can use a method Arrays.asList
that takes var-args
and returns a fixed size List
supported by an array. Thus, you cannot add any item to this list. In addition, any modification made by the items List
will be reflected back to 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 need to pass it in the constructor ArrayList
.
List<String> list = new ArrayList<String>(Arrays.asList(arrayOfStrings));
source to share
You can use a static method Arrays.asList()
.
For example:
String[] arrayOfStrings = {"this", "is", "an", "array", "of", "strings"};
List<String> list = Arrays.asList(arrayOfStrings);
Note that you are creating a fixed-size list, a "fallback array" this way. If you want to extend it, you will need to do the following path:
String[] arrayOfStrings = {"this", "is", "an", "array", "of", "strings"};
List<String> list = new ArrayList<String>(Arrays.asList(arrayOfStrings));
source to share
You can use asList ()
Arrays.asList (T ... a) Returns a fixed-size list supported by the specified array.
http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html
source to share