I have below code snippet to add the elements in ArrayList
List <Integer> myList = new ArrayList();
myList.add(1);
myList.add(2);
myList.add(3);
myList.add(4);
I am looking for more readable and elegant way to add the elements in ArrayList
, something like below. I know below is not allowed but is there any other readable/elegant way?
myList.add(1).add(2).add(3).add(4)
UPDATE:- i am on java 1.6
In order to optimize the performance of ArrayLists, it is advisable to set a large enough initial capacity when initializing an ArrayList to incorporate all your data. This will allocate a large enough chunk of memory so that you will probably not need to perform the allocation process again.
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);
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