Initialization of an ArrayList in one line
Explanation
To Initialization of an ArrayList in one line we can make it simple just by declaring it as a List
.
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
Or in case if you just have only one element at that time use:
List<String> places = Collections.singletonList("Buenos Aires");
This can mean that places is immutable and if you try to change it will cause an exception called as UnsupportedOperationException
which will be thrown.
To make a list mutable that is a concrete ArrayList
. you can simply create an ArrayList
from the immutable list:
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Also read, How do I loop through or enumerate a JavaScript object?