How to initialize List<String> object in Java?
To initialize a List<String>
object in Java, you can use one of the following approaches:
- Using the
new
keyword:
List<String> list = new ArrayList<>();
This will create an empty ArrayList object. You can then add elements to the list using the add
method:
list.add("apple");
list.add("banana");
list.add("orange");
- Using the
Arrays.asList
method:
List<String> list = Arrays.asList("apple", "banana", "orange");
This will create a list with the specified elements. Note that the list created using this method is fixed-size and cannot be modified.
- Using the
Collections.singletonList
method:
List<String> list = Collections.singletonList("apple");
This will create a list with a single element. The list created using this method is also fixed-size and cannot be modified.