initial data for list java

www.lau‮moc.irutt‬
initial data for list java

There are several ways to initialize a list with data in Java. Here are a few examples:

  1. Using an array:
String[] array = {"apple", "banana", "cherry"};
List<String> list = Arrays.asList(array);
  1. Using a List implementation constructor:
List<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "cherry"));
  1. Using the add() method:
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
  1. Using the 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.

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