Collection Interface toArray() Method

Collection Interface toArray() Method


Posted in : Java Posted on : November 27, 2010 at 5:31 PM Comments : [ 0 ]

Using this method we can store all elements from the invoking collection in an array.

Collection Interface toArray() Method:

Using this method we can store all elements from the invoking collection in an array. It return an array that contain copies of the collection elements.

Syntax :

Object[ ] toArray( );

Example :

import java.util.ArrayList;
import java.util.Collection;

public class collectioninterfacetoarraymethod {
public static void main(String args[]) {

Collection<String> arraylist = new ArrayList<String>();

arraylist.add("Raj");
arraylist.add("Singh");

System.out.println("Contents of arraylist: " + arraylist);

String arr[] = new String[arraylist.size()]; 
arr = arraylist.toArray(arr);
System.out.println("Contents of array: ");
for(int i=0; i<(arraylist.size()); i++){
System.out.println(arr[i]);
}
}
}

Output :

Contents of arraylist: [Raj, Singh]
Contents of array:
      Raj
      Singh

Download This example code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics