I wanted to create a list of options for testing purposes. At first, I did this:
ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
Then, I refactored the code as follows:
ArrayList<String> places = new ArrayList<String>(
Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Is there a better way to do this?
Best Answer
It would be simpler if you were to just declare it as a
List
- does it have to be an ArrayList?Or if you have only one element:
This would mean that
places
is immutable (trying to change it will cause anUnsupportedOperationException
exception to be thrown).To make a mutable list that is a concrete
ArrayList
you can create anArrayList
from the immutable list: