Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Converting a Collection to an Array

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:

  1. The type of the array argument determines the type of array returned.

  2. If the array is big enough (you can control this with the Collection’s size( ) method), then this array is filled and returned. If the array is not big enough, a new array is allocated instead. If you provide an array and there are objects in the Collection that cannot be casted to this type, then you get an ArrayStoreException.

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata