Wednesday, May 18, 2011

Array Operations on collections in java

The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input. They allow the contents of a Collection to be translated into an array. The simple form with no arguments creates a new array of Object. The more complex form allows the caller to provide an array or to choose the runtime type of the output array. For example, suppose c is a Collection The following snippet dumps the contents of c into a newly allocated array of Object whose length is identical to the number of elements in c:
Object[] a = c.toArray();
Suppose c is known to contain only strings. The following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the number of elements in c:

String[] a = (String[]) c.toArray(new String[0]);

No comments:

Post a Comment

Chitika