initialize arraylist in 1 line in java

‮‬https://www.lautturi.com
initialize arraylist in 1 line in java

To initialize an ArrayList in a single line of code in Java, you can use the ArrayList constructor or the of() method (Java 9 and later).

Here is an example of how to initialize an ArrayList using the constructor:

List<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "cherry"));

This creates a new ArrayList object and initializes it with the elements "apple", "banana", and "cherry".

Here is an example of how to initialize an ArrayList using the of() method (Java 9 and later):

List<String> list = List.of("apple", "banana", "cherry");

In both examples, the list variable is initialized with a new ArrayList object containing the elements "apple", "banana", and "cherry".

Note that the List interface is an interface, and as such, you cannot create an instance of it directly. Instead, you need to use a concrete implementation of the List interface, such as ArrayList, to create a List object.

For more information on the List interface and the ArrayList class in Java, you can refer to the Java documentation.

Created Time:2017-11-01 22:29:52  Author:lautturi