Java how to put array in array list

Java how to put array in array list

To put an array in an ArrayList in Java, you can use the addAll method of the ArrayList class and pass the array as an argument. The addAll method takes a collection as an argument and adds all the elements of the collection to the ArrayList.

Here is an example of how you can put an array in an ArrayList in Java:

refe‮al:ot r‬utturi.com
import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample {
    public static void main(String[] args) {
        String[] array = {"apple", "banana", "cherry"};
        ArrayList<String> list = new ArrayList<>();

        list.addAll(Arrays.asList(array));
    }
}

In this example, the main method declares an array of strings and an ArrayList of strings. It then uses the addAll method and passes the array as an argument, wrapped in a call to the Arrays.asList method, which converts the array into a List.

This code will add all the elements of the array to the ArrayList, resulting in a list that contains the elements of the array.

Keep in mind that this is just one way to put an array in an ArrayList in Java. You can use different techniques and data structures to achieve the same result, such as using a loop to add the elements of the array one by one to the ArrayList or using the Collections.addAll method to add the elements of the array in a single call.

Created Time:2017-11-03 23:27:11  Author:lautturi