HomeCore Java

Converting ArrayList To Array

Like Tweet Pin it Share Share Email

Learn how to convert an ArrayList object to an Array. In this example we will demonstrate you how to convert an ArrayList object to an Array.

Mostly, we will use toArray() method to convert an ArrayList into an Array. But there are many ways to convert an an ArrayList object to an Array.

At the end of this ArrayList to an Array conversion example you will understand how to convert an ArrayList to an Array. Moreover, 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()]);

Comments (1)

Leave a Reply

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