I am trying to pass a string array as an argument to the constructor of Wetland class;
I don’t understand how to add the elements of string array to the string array list.
import java.util.ArrayList;
public class Wetland {
private String name;
private ArrayList<String> species;
public Wetland(String name, String[] speciesArr) {
this.name = name;
for (int i = 0; i < speciesArr.length; i++) {
species.add(speciesArr[i]);
}
}
}
You already have built-in method for that: –
NOTE: – You should use
List<String> speciesnotArrayList<String> species.Arrays.asListreturns a differentArrayList->java.util.Arrays.ArrayListwhich cannot be typecasted tojava.util.ArrayList.Then you would have to use
addAllmethod, which is not so good. So just useList<String>NOTE: – The list returned by
Arrays.asListis a fixed size list. If you want to add something to the list, you would need to create another list, and useaddAllto add elements to it. So, then you would better go with the 2nd way as below: –