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 |

[ 0 ] Comments