import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListInitialization {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry"));
System.out.println(list);
}
}
Explanation:
This Java program demonstrates initializing a `List` with predefined elements and printing it. The program starts by importing necessary classes from the Java Collections Framework: `ArrayList`, `Arrays`, and `List`. Within the `main` method, a new `ArrayList` is created and populated with a fixed set of `String` elements ("Apple", "Banana", "Cherry") using `Arrays.asList()`. This method generates a list from the specified elements, which is then passed to the `ArrayList` constructor. This approach allows the creation of a mutable `List` that supports adding or removing elements, unlike the fixed-size list directly returned by `Arrays.asList()`. Finally, the program prints the contents of the list to the console, showcasing the successfully initialized list with its elements. This simple example highlights the combination of `Arrays.asList()` and `ArrayList` to initialize and manipulate collections in Java.