How To Create ArrayList From Array?

In this Tutorial, we will discuss How to Create ArrayList from the array. We can do so in three ways first simply iterate the array and keep it stored in ArrayList one by one, Another way can be passing the array in arguments to convert it as a list and then convert the list in to arraylist and we can also some in build method like the collection.add to create an array as arraylist.

ArrayList From Array

There are different methods to do Let’s discuss all the possible ways to convert array to arraylist.

Ways To Convert Array To ArrayList

We will discuss three of those ways to convert.

Using Arrays.asList() method

In this method, we pass the array as an object to the method to get the list out of the array and then pass it as an argument to the arraylist. Here we are going o pass it twice as first we convert it to list and then at last arrayList.

Collections.addAll() method

We can also directly convert to arraylist by using collections, where we use the inbuilt library of Collection() to convert array to ArrayList. Here we create a list before and then pass it in an argument to convert.

we will see it using an example below to understand better and get an example.

Iteration method

In this method, we iterate the whole array one by one and keep storing each element individually in an arraylist using for loop to access each elements of an array and store them in an array list.

We create an arraylist before in this method.

Let us take the examples of each of the given above examples and understand better all the ways to convert array to arraylist.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Tester {
   public static void main(String args[]) {
      String[] array = {"a", "b", "c", "d", "e"};

      //Method 1
      List<String> list = Arrays.asList(array);          
      System.out.println(list);

      //Method 2
      List<String> list1 = new ArrayList<String>();
      Collections.addAll(list1, array);
      System.out.println(list1);

      //Method 3
      List<String> list2 = new ArrayList<String>();
      for(String text:array) {
         list2.add(text);
      }
      System.out.println(list2);
   }  
}

Here we can see all three examples explain how they are converting an array to an arraylist.

 

Learn More about How To Create ArrayList From Array? at: Array List from array

And also visit Java Tutorials  to get the list of problems solved and help yourself in solving the problems also visit Python Tutorial : Getting started with Python Programming to learn more about python and other topics follow these pages .

Leave a Comment

%d bloggers like this: