Date: 2014nov3
Update: 2025sep29
Language: Java
Keywords: init
Q. Java: Initialize an ArrayList of Strings in one statement
A. Use things in java.util.Arrays as shown in this full example:
import java.util.ArrayList;
import java.util.Arrays;
class Demo {
// One way
static ArrayList<String> colors1 = new ArrayList<String>(Arrays.asList("red", "green", "blue"));
// Another way
static ArrayList<String> colors2 = new ArrayList<String>(Arrays.asList(new String[] {"red", "green", "blue"}));
// But if its constants you can just use a regular array
static final String colors3[] = { "red", "green", "blue" };
public static final void main(String args[]) {
System.out.println("colors1=" + colors1);
System.out.println("colors2=" + colors2);
System.out.println("colors3=" + Arrays.toString(colors3));
}
}
Output:
colors1=[red, green, blue]
colors2=[red, green, blue]
colors3=[red, green, blue]