I wanted to create a list of options for testing purposes. At first, I did this:
ArrayList places = new ArrayList();
places.add(\
Collections.singletonList(messageBody)
If you'd need to have a list of one item!
Collections is from java.util package.
It would be simpler if you were to just declare it as a List
- does it have to be an ArrayList?
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
Or if you have only one element:
List<String> places = Collections.singletonList("Buenos Aires");
This would mean that places
is immutable (trying to change it will cause an UnsupportedOperationException
exception to be thrown).
To make a mutable list that is a concrete ArrayList
you can create an ArrayList
from the immutable list:
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Java 9 has the following method to create an immutable list:
List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");
which is easily adapted to create a mutable list, if required:
List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
Similar methods are available for Set
and Map
.
For me Arrays.asList() is the best and convenient one. I always like to initialize that way. If you are a beginner into Java Collections then I would like you to refer ArrayList initialization
You could create a factory method:
public static ArrayList<String> createArrayList(String ... elements) {
ArrayList<String> list = new ArrayList<String>();
for (String element : elements) {
list.add(element);
}
return list;
}
....
ArrayList<String> places = createArrayList(
"São Paulo", "Rio de Janeiro", "Brasília");
But it's not much better than your first refactoring.
For greater flexibility, it can be generic:
public static <T> ArrayList<T> createArrayList(T ... elements) {
ArrayList<T> list = new ArrayList<T>();
for (T element : elements) {
list.add(element);
}
return list;
}
About the most compact way to do this is:
Double array[] = { 1.0, 2.0, 3.0};
List<Double> list = Arrays.asList(array);