-2

Is this formula is legal in java to declare ArrayList

List<Integer> list1 = new ArrayList<Integer>() {1,2,3,4,5};
Scorpion
  • 567
  • 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
  • 310,138
  • 72
  • 642
  • 762
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,715
  • 4
  • 34
  • 68
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,638
  • 5
  • 30
  • 42
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,480
  • 2
  • 27
  • 40