learningboy learningboy - 9 days ago 5
Java Question

Creating an ArrayList with values mentioned at the time of creation

If I were to create an array, and initialize it with values, I would do

int[] a = {1,2,3,4,5};


I would like to do the same with ArrayList, and have something like

ArrayList<Integer> al = new ArrayList<Integer>().addAll(Arrays.asList(1,2,3,4,5));


The above line of code does not work, I understand. I'm trying to convey what I am hoping to achieve. Is there a way to do this in Java, without having to do something like

ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);al.add(2);al.add(3);al.add(4);al.add(5);


Or

ArrayList<Integer> alArrayList = new ArrayList<>();
alArrayList.addAll( Arrays.asList( 1,2,3,4,5 ) );

Answer

Use the constructor which takes a Collection as parameter. This constructs a list containing the elements of the specified collection

ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println(list);

OR

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

If you will see the implementation of Arrays.asList() it returns a new Arraylist containing the specified elements.

@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}