This article was last updated on : November 4th, 2016 at 3:59 am

Converting ArrayList To Array

In this example we will demonstrate how to convert an ArrayList object to an Array. We will use toArray() method to convert an ArrayList into an Array.At the end of this ArrayList to an Array conversion example you will understand how to convert an ArrayList to an Array, How toArray() method works.


package com.sitenol.arrylisttoarray;
import java.util.ArrayList;
public class ArrayListToArray {
public static void main(String args []){
ArrayList arrayList = new ArrayList();
arrayList.add("array1");
arrayList.add("array2");
arrayList.add("array3");
arrayList.add("array4");
arrayList.add("array5");
System.out.println(arrayList);
Object[] arrayObj = (Object[])arrayList.toArray(new String[arrayList.size()]);
System.out.println(arrayObj);
for(int i=0 ; i<arrayObj.length; i++){
System.out.println("The values in the array is - "+arrayObj[i]);
}
}
}

In this example we are creating a list of String objects. Here we are converting this String ArrayList to Array by using toArray() method. Please line number 15.

Object[] arrayObj = (Object[])arrayList.toArray(new String[arrayList.size()]);
So the above example was done for String type ArrayList.
What to do when we have list of Integer type object

So in integer type list all the values will be Integer object type so while creating Array of Integer type we have do like this

Object[] arrayObj = (Object[])arrayList.toArray(new Integer[arrayList.size()]);

Share this post:

Recent Posts

One Comment

  1. Avatar for Tarun Singh
    Dheeraj says:

    It’s an informative post.

Leave a Comment