Add elements in ArrayList in more readable way
When you know the elements prior to instantiating:
List<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
or if you want to add them to an existing list:
List<Integer> myList = new ArrayList<>();
// do stuff
myList.addAll(Arrays.asList(1, 2, 3, 4));
To make it more readable, you can
import static java.util.Arrays.asList;
and simply use
List<Integer> myList = new ArrayList<>(asList(1, 2, 3, 4));
or
List<Integer> myList = new ArrayList<>();
// do stuff
myList.addAll(asList(1, 2, 3, 4));
In case you know that you never ever want to add more elements to the list, you can simply write
List<Integer> myList = Arrays.asList(1, 2, 3, 4);
or with the static import:
List<Integer> myList = asList(1, 2, 3, 4);
Guava way(though List is immutable):
ImmutableList<Integer> myList = ImmutableList.<Integer>builder()
.add(1)
.add(2)
.add(3)
.build();
or this way:
List <Integer> myList = Lists.newArrayList(1,2,3);
or
List <Integer> myList = Ints.asList(1,2,3);
If you find this readable, here's one more way
List<Integer> list = new ArrayList<Integer>() {{
add(1);add(2);add(3);
}};