learningboy learningboy - 2 months ago 14
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>();


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


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));


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.

public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);