Java ArrayList to an Object Array Example

In this tutorial we will learn how to copy all the elements of the ArrayList to an Array. We will be using toArray() method of java.util.ArrayList class.

Signature

public Object[] toArray()

This method returns an Object array containing all of the elements in this list in proper sequence.

Example

The following example shows the usage of toArray() method.

import java.util.ArrayList;

public class ElementsOfArrayListToArrayExample 
{
	public static void main(String[] args) {
	    //create an ArrayList object
	    ArrayList arrayList = new ArrayList();
	   
	    //Add elements to ArrayList
	    arrayList.add("Element1");
	    arrayList.add("Element2");
	    arrayList.add("Element3");
	    arrayList.add("Element4");
	 	   
	    /*
	      For copying elements of java ArrayList object into array we use
	      Object[] toArray() method.
	    */
	   
	    Object[] objArray = arrayList.toArray();
	   
	    //display contents of Object array
	    System.out.println("Object Array will now have all the elements of ArrayList");
	    for(Object val :objArray)
	    {
	    	System.out.println(val);
	    }
	}
}

Output

Object Array will now have all the elements of ArrayList
Element1
Element2
Element3
Element4

Leave a Reply

Your email address will not be published. Required fields are marked *