Java Cookbook, Second Edition
Problem
You have a Collection but you need a Java language array. Solution
Use the Collection method toArray( ) . Discussion
If you have an ArrayList or other Collection and you need a Java language array, you can get it just by calling the Collection's toArray( ) method. With no arguments, you get an array whose type is Object[]. You can optionally provide an array argument, which is used for two purposes:
Example 7-1 shows code for converting an ArrayList to an array of type Object. Example 7-1. ToArray.java
import java.util.*; /** ArrayList to array */ public class ToArray { public static void main(String[] args) { ArrayList al = new ArrayList( ); al.add("Blobbo"); al.add("Cracked"); al.add("Dumbo"); // al.add(new Date( )); // Don't mix and match! // Convert a collection to Object[], which can store objects // of any type. Object[] ol = al.toArray( ); System.out.println("Array of Object has length " + ol.length); // This would throw an ArrayStoreException if the line // "al.add(new Date( ))" above were uncommented. String[] sl = (String[]) al.toArray(new String[0]); System.out.println("Array of String has length " + sl.length); } } |