Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add elements in ArrayList in more readable way

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

like image 976
emilly Avatar asked May 14 '13 09:05

emilly


People also ask

How can an ArrayList improve performance?

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.


1 Answers

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);
like image 172
jlordo Avatar answered Sep 22 '22 21:09

jlordo