Jesper de Jong wrote:There are some important things to note with the solutions given above:
Garrett's solution, with Arrays.asList() is efficient because it doesn't need to copy the content of the array. This method returns a List that is a "view" onto the array - a wrapper that makes the array look like a list. When you change an element in the list, the element in the original array is also changed. Note that the list is fixed size - if you try to add elements to the list, you'll get an exception.
Ernest's solution: new ArrayList(Arrays.asList(myArray)); copies the content of the array to a new ArrayList. The copy is ofcourse independent of the array, and you can add, remove etc. elements as you like.
Janarthan's solution, with Collections.addAll(myList, myStringArray); is essentially the same as Ernest's solution.
If you only need read access to the array as if it is a List and you don't want to add or remove elements from the list, then use Garrett's solution. Otherwise use Ernest's or Janarthan's solution.
As of Java 8:
String [] strings = {"one", "two", "three"};
Note, this is already explained in the post by Jesper de Jong. This is because (from the API javadocs) the method
Arrays.asList() returns a fixed-size list (list_1 or list_1a) backed by the specified array. Of course, this can be overcome by using this construct:
List<String> list_1c = new ArrayList<>(Arrays.asList(strings));
Using Streams:
Note, the statement above at
line 3 (creating list_2c) allows to specify the type of
List implementation, in this case a
LinkedList.
NOTE: For the above statements building the
List, instead of an array, varargs can be specified. The behaviour remains the same.
SCJP 5, OCPJP 7, 8, SCJD 5, SCWCD 4, SCBCD 5, SCJWS 4, IBM OOAD 833 & 834, MongoDB Developer