To initialize an ArrayList
in Java, you can use the ArrayList
constructor or the add()
method.
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 add()
method:
List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry");
In this example, the list
variable is initialized with a new ArrayList
object, and the elements "apple", "banana", and "cherry" are added to the list using the add()
method.
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.