Java ArrayList convert to an array

Introduction

To convert an ArrayList into an array in Java

String ia[] = new String[al.size()];  //define an array with the proper size
ia = al.toArray(ia);   //call toArray() from arrayList

Full source

import java.util.ArrayList;
import java.util.Arrays; 
 
public class Main { 
  public static void main(String args[]) { 
    // Create an array list. 
    ArrayList<String> al = new ArrayList<String>(); 
     // w  w  w  .  j  a v a2  s  . c  o m
    // Add elements to the array list. 
    al.add("SQL"); 
    al.add("Java"); 
    al.add("Javascript"); 
    al.add("CSS"); 
    al.add("HTML"); 
    al.add("Demo2s.com"); 
    al.add(1, "Hi"); 
 
    System.out.println(al);
    
    // Get the array. 
    String ia[] = new String[al.size()];  
    ia = al.toArray(ia);  
    
    System.out.println(Arrays.toString(ia));
  } 
}



PreviousNext

Related