0

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

3 Answers3

2

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);
}
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
0
import java.util.ArrayList;
import java.util.Arrays;

public class Demo{
 public static void main(String[] args) {
    Integer[] a = { 10, 11, 41, 2, 43, 33, 4, 5, 67, 70, 7 };
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.addAll(Arrays.asList(a));
    System.out.println(list);
 }
}
Rohit Gaikwad
  • 3,677
  • 3
  • 17
  • 40
0

You can simply do following:

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

or

ArrayList<Integer> al = (ArrayList<Integer>)Arrays.asList(1,2,3,4,5);
Saravana
  • 12,647
  • 2
  • 39
  • 57
Mahipal
  • 900
  • 1
  • 5
  • 7
  • `ArrayList al = (ArrayList)Arrays.asList(1,2,3,4,5)` will fail at runtime with `java.lang.ClassCastException` – Saravana Dec 01 '16 at 05:05