Is this formula is legal in java to declare ArrayList
List<Integer> list1 = new ArrayList<Integer>() {1,2,3,4,5};
Is this formula is legal in java to declare ArrayList
List<Integer> list1 = new ArrayList<Integer>() {1,2,3,4,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));
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));
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
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 }));