You already have built-in method for that: -
List<String> species = Arrays.asList(speciesArr);
NOTE: - You should use List<String> species
not ArrayList<String> species
.
Arrays.asList
returns a different ArrayList
-> java.util.Arrays.ArrayList
which cannot be typecasted to java.util.ArrayList
.
Then you would have to use addAll
method, which is not so good. So just use List<String>
NOTE: - The list returned by Arrays.asList
is a fixed size list. If you want to add something to the list, you would need to create another list, and use addAll
to add elements to it. So, then you would better go with the 2nd way as below: -
String[] arr = new String[1];
arr[0] = "rohit";
List<String> newList = Arrays.asList(arr);
// Will throw `UnsupportedOperationException
// newList.add("jain"); // Can't do this.
ArrayList<String> updatableList = new ArrayList<String>();
updatableList.addAll(newList);
updatableList.add("jain"); // OK this is fine.
System.out.println(newList); // Prints [rohit]
System.out.println(updatableList); //Prints [rohit, jain]