Initializing ArrayList with some predefined values [duplicate]
try this
new String[] {"One","Two","Three","Four"};
or
List<String> places = Arrays.asList("One", "Two", "Three");
ARRAYS
Double brace initialization is an option:
List<String> symbolsPresent = new ArrayList<String>() {{
add("ONE");
add("TWO");
add("THREE");
add("FOUR");
}};
Note that the String
generic type argument is necessary in the assigned expression as indicated by JLS §15.9
It is a compile-time error if a class instance creation expression declares an anonymous class using the "<>" form for the class's type arguments.
How about using overloaded ArrayList constructor.
private ArrayList<String> symbolsPresent = new ArrayList<String>(Arrays.asList(new String[] {"One","Two","Three","Four"}));
You can also use the varargs syntax to make your code cleaner:
Use the overloaded constructor:
ArrayList<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c"));
Subclass ArrayList in a utils module:
public class MyArrayList<T> extends ArrayList<T> {
public MyArrayList(T... values) {
super(Arrays.asList(values));
}
}
ArrayList<String> list = new MyArrayList<String>("a", "b", "c");
Or have a static factory method (my preferred approach):
public class Utils {
public static <T> ArrayList<T> asArrayList(T... values) {
return new ArrayList<T>(Arrays.asList(values));
}
}
ArrayList<String> list = Utils.asArrayList("a", "b", "c");
import com.google.common.collect.Lists;
...
ArrayList<String> getSymbolsPresent = Lists.newArrayList("item 1", "item 2");
...