How to declare an ArrayList with values?
To declare an ArrayList with values in Java, you can use the Arrays.asList
method and pass it an array or a list of values.
Here's an example of how you can declare an ArrayList with values using the Arrays.asList
method:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
System.out.println(list);
}
}
This code defines an array of strings and converts it to a List
using the Arrays.asList
method. It then creates an ArrayList object and initializes it with the values in the list using the ArrayList constructor.
Alternatively, you can also use the addAll
method to add the values from an array or another collection to an ArrayList:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.addAll(Arrays.asList("a", "b", "c"));
System.out.println(list);
}
}
I hope this helps! Let me know if you have any questions.