There are several ways to convert an array to an ArrayList in Java. Here are three of the most common methods:
Using Arrays.asList()
The Arrays.asList() method is the simplest way to convert an array to an ArrayList. It takes an array as its only argument and returns a List object that contains the elements of the array.
For example, the following code converts an array of strings to an ArrayList of strings:
String[] array = { "Hello", "World" };
List<String> list = Arrays.asList(array);
The list object returned by Arrays.asList() is backed by the original array. This means that if you modify the original array, the changes will be reflected in the list object.
Using Collections.addAll()
The Collections.addAll() method is another way to convert an array to an ArrayList. It takes two arguments: a List object and an array. The method adds all of the elements of the array to the List object.
For example, the following code converts an array of strings to an ArrayList of strings:
String[] array = { "Hello", "World" };
List<String> list = new ArrayList<>();
Collections.addAll(list, array);
The advantage of using Collections.addAll() over Arrays.asList() is that you can create a new ArrayList object and then add the elements of the array to it. This gives you more control over the type of List object that is created.
Using an iteration loop
The third way to convert an array to an ArrayList is to use an iteration loop. This method is the most flexible, but it is also the most time-consuming.
To convert an array to an ArrayList using an iteration loop, you first need to create a new ArrayList object. Then, you need to iterate through the array and add each element to the ArrayList object.
For example, the following code converts an array of strings to an ArrayList of strings:
String[] array = { "Hello", "World" };
List<String> list = new ArrayList<>();
for (String element : array) {
list.add(element);
}
This method is the most flexible because you can use it to convert any type of array to any type of List object. However, it is also the most time-consuming because you need to iterate through the entire array.
No comments:
Post a Comment