Java program to convert a list to an array


The List object provides a method known as toArray(). This method accepts an empty array as argument, converts the current list to an array and places in the given array. To convert a List object to an array −

  •  Create a List object.
  •  Add elements to it.
  •  Create an empty array with size of the created ArrayList.
  •  Convert the list to an array using the toArray() method, bypassing the above-created array as an argument to it.
  •  Print the contents of the array.

Example

Live Demo

import java.util.ArrayList;
public class ListToArray {
   public static void main(String args[]){
      ArrayList<String> list = new ArrayList<String>();
      list.add("Apple");
      list.add("Orange");
      list.add("Banana");

      System.out.println("Contents of list ::"+list);
      String[] myArray = new String[list.size()];
      list.toArray(myArray);

      for(int i=0; i<myArray.length; i++){
         System.out.println("Element at the index "+i+" is ::"+myArray[i]);
      }
   }
}

Output

Contents of list ::[Apple, Orange, Banana]
Element at the index 0 is ::Apple
Element at the index 1 is ::Orange
Element at the index 2 is ::Banana

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 13-Mar-2020

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements