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

Java 8Object Oriented ProgrammingProgramming

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);
}
raja
Published on 10-Jan-2019 13:51:53
Advertisements