Convert ArrayList to an Array in Java


Write a Java Program to convert arraylist to an array.

Click Here to View the Solution!
import java.util.ArrayList;
class ArrayListToArray {
  public static void main(String[] args) {
    ArrayList<String> languages= new ArrayList<>();
    // Add elements in the arraylist
    languages.add("New York");
    System.out.println("ArrayList: " + languages);
    // Create a String type array 
    String[] arr = new String[languages.size()];
    // Convert ArrayList into the string array
    System.out.print("Array: ");
    for(String item:arr) {
      System.out.print(item+", ");
Click Here to View the Output!
 ArrayList: [New York, London, Washington]
 Array: New York, London, Washington, 
Click Here to View the Explanation!
  • In this program, firstly an arraylist called languages has been created which is to be converted into an array afterwards.
  • The code for converting this arraylist into an array is given by: languages.toArray(arr);
  • toArray() method is used for converting ‘languages’ into an array and the converted version is then stored in arr which is a string type array variable.
  • If the method toArray() doesn’t have any argument passed to it, then it will return an array of the type object.
%d bloggers like this: