Convert an ArrayList to an Array with zero length Array in Java


An ArrayList can be converted into an Array using the java.util.ArrayList.toArray() method. This method takes a single parameter i.e. the array of the required type into which the ArrayList elements are stored and it returns an Array that contains all the elements of the ArrayList in the correct order.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List<String> aList = new ArrayList<String>();
      aList.add("James");
      aList.add("Harry");
      aList.add("Susan");
      aList.add("Emma");
      aList.add("Peter");
      String[] arr = aList.toArray(new String[0]);
      System.out.println("The array elements are: ");
      for (String i : arr) {
         System.out.println(i);
      }
   }
}

Output

The array elements are:
James
Harry
Susan
Emma
Peter

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to this ArrayList. A code snippet which demonstrates this is as follows −

List<String> aList = new ArrayList<String>();
aList.add("James");
aList.add("Harry");
aList.add("Susan");
aList.add("Emma");
aList.add("Peter");

The method ArrayList.toArray() is used to convert the ArrayList into an Array. Then the Array elements are displayed using a for loop. A code snippet which demonstrates this is as follows −

String[] arr = aList.toArray(new String[0]);
System.out.println("The array elements are: ");
for (String i : arr) {
   System.out.println(i);
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements