Collections

how to convert an ArrayList to simple Array using Collections in java
Previous Home Next

 

In the following example we will see how can we convert a ArrayList  to a linear Array.

In this example we have created a class CollectionExample. For using ArrayList we have
to import the java.util package.
 For converting an ArrayList to a linear array we have to use the toArray() method defined in the class java.util.ArrayList.

In the following example we have created an ArrayList. Then we added some elements to that array, also we have created a String type array of the same size as of the ArrayList. Since the toArray() returns the object array  so we also created on Object array to store the elements of the ArrayList. After that we have stored the elements of the Object to the String array via typecasting.

The following statement converts the ArrayList al to linear array in the code:
 Object[] objarr=al.toArray(); 

 
package r4r.co.in;
import java.util.ArrayList;
import java.util.Iterator;


public class CollectionExample {

/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub


ArrayList<String> al=new ArrayList<String>(); // creating an ArrayList named al
al.add("r4r"); // adding string objects to the arraylist
al.add("development");
al.add("tutorials");
al.add("shashi");
al.add("s/w engineer");
System.out.println("The size of the arraylist is: "+al.size()); // determining the length of the arraylist

System.out.println("The contents of the list are :"+al); // showing the contents of the arraylist

String[] arr=new String[(al.size())]; // creating an array of String to match the size of the arraylist al
Object[] objarr=al.toArray(); // creating an object array objarr to contain the object array returned by the toArray() method on al
for(int i=0;i<al.size();i++)
{
arr[i]=(String)objarr[i]; // typecasting the object array elements to the String types

}
System.out.println("Now the elements of the array are displayed as :");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]); // diplaying the array elements
}

}


}

The output of the above program is as follows:

The size of the arraylist is: 5
The contents of the list are :[r4r, development, tutorials, shashi, s/w engineer]
Now the elements of the array are displayed as :
r4r
development
tutorials
shashi
s/w engineer

Previous Home Next