There are several ways to initialize a list with data in Java. Here are a few examples:
String[] array = {"apple", "banana", "cherry"}; List<String> list = Arrays.asList(array);
List
implementation constructor:List<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "cherry"));
add()
method:List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry");
of()
method (Java 9 and later):List<String> list = List.of("apple", "banana", "cherry");
In these examples, the list
variable is initialized with a List
object containing the strings "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 its implementations in Java, you can refer to the Java documentation.