I have an sample program as shown.
I want my ArrayList
symbolsPresent
to be initialized with some predefined symbols: ONE, TWO, THREE, and FOUR.
symbolsPresent.add("ONE"); symbolsPresent.add("TWO"); symbolsPresent.add("THREE"); symbolsPresent.add("FOUR");
import java.util.ArrayList; public class Test { private ArrayList<String> symbolsPresent = new ArrayList<String>(); public ArrayList<String> getSymbolsPresent() { return symbolsPresent; } public void setSymbolsPresent(ArrayList<String> symbolsPresent) { this.symbolsPresent = symbolsPresent; } public static void main(String args[]) { Test t = new Test(); System.out.println("Symbols Present is" + t.symbolsPresent); } }
Is that possible?
To initialize an ArrayList with multiple items in a single line can be done by creating a List of items using Arrays. asList(), and passing the List to the ArrayList constructor. In the given example, we are adding two strings “a” and “b” to the ArrayList.
Java developers use the Arrays. asList() method to initialize an ArrayList. Using asList() allows you to populate an array with a list of default values. This can be more efficient than using multiple add() statements to add a set of default values to an ArrayList.
To initialize an arraylist in single line statement, get all elements in form of array using Arrays. asList method and pass the array argument to ArrayList constructor. ArrayList<String> names = new ArrayList<String>( Arrays.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With