-2

Is this formula is legal in java to declare ArrayList

List<Integer> list1 = new ArrayList<Integer>() {1,2,3,4,5};
Scorpion
  • 557
  • 4
  • 19

4 Answers4

5

Java 8 provides several alternatives, such as:

List<Integer> list1 = IntStream.of(1, 2, 3, 4, 5).boxed().collect(toList());
List<Integer> list1 = IntStream.rangeClosed(1, 5).boxed().collect(toList());

With Java 7 you need to use:

List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5); //can't add or remove
List<Integer> list1 = new ArrayList<> (Arrays.asList(1, 2, 3, 4, 5));
assylias
  • 297,541
  • 71
  • 621
  • 741
0

No you cant do use it like that Have a read of both this and this. These two pages would clear all your doubts regarding declaring arrayLists. Or if you just want the solution, List<Integer> list1= new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));

Community
  • 1
  • 1
Daksh Shah
  • 2,477
  • 4
  • 32
  • 64
0

No, But there are other ways to do that,

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

or you an use anonymous inner class

Orhan Obut
  • 8,288
  • 5
  • 29
  • 41
0

You can do it with that array initialization notation like this:

ArrayList<Integer> list1 = new ArrayList(Arrays.asList(new Integer[] {1, 2, 3, 4, 5 }));
Martin Dinov
  • 8,190
  • 2
  • 26
  • 37