How to cast a list of strings to a string array?


The java.util.ArrayList.toArray() method returns an array containing all of the elements in this list in proper sequence (from first to last element).This acts as bridge between array-based and collection-based APIs.

You can convert a list to array using this method of the List class −

Example

Live Demo

import java.util.ArrayList;
import java.util.List;

public class ListOfStringsToStringArray {
   public static void main(String args[]) {
      List<String> list = new ArrayList<String>();
      
      list.add("JavaFX");
      list.add("HBase");
      list.add("OpenCV");
      
      String[] myArray = new String[list.size()];
      
      list.toArray(myArray );
      System.out.println("Contents of the String array are :: ");

      for(int i = 0; i<myArray.length; i++) {
         System.out.println(myArray[i]);
      }
   }
}

Output

Contents of the String array are ::
JavaFX
HBase
OpenCV

Swarali Sree
Swarali Sree

I love thought experiments.

Updated on: 30-Jul-2019

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements