How to create ArrayList from array in Java
To create an ArrayList from an array in Java, you can use the ArrayList constructor that takes an Collection
as an argument. You can pass the array to the Arrays.asList()
method, which returns a List
view of the array, and then pass the resulting list to the ArrayList constructor. Here's an example:
String[] array = {"a", "b", "c"};
List<String> list = new ArrayList<>(Arrays.asList(array));
Alternatively, you can use the Collections.addAll()
method to add the elements of the array to an existing ArrayList:
String[] array = {"a", "b", "c"};
List<String> list = new ArrayList<>();
Collections.addAll(list, array);
Both of these approaches create a new ArrayList and add the elements of the array to it. The resulting list is modifiable, so you can add or remove elements from it as needed.
Note that the Arrays.asList()
method returns a fixed-size list, so you cannot use it to add or remove elements from the list. If you need a modifiable list, you should use one of the other approaches.