The easiest way to transform collection to array?

Roman picture Roman · Jul 20, 2010 · Viewed 165.6k times · Source

Suppose we have a Collection<Foo>. What is the best (shortest in LoC in current context) way to transform it to Foo[]? Any well-known libraries are allowed.

UPD: (one more case in this section; leave comments if you think it's worth to create another thread for it): What about transforming Collection<Foo> to Bar[] where Bar has constructor with 1 parameter of type Foo i.e. public Bar(Foo foo){ ... } ?

Answer

doublep picture doublep · Jul 20, 2010

Where x is the collection:

Foo[] foos = x.toArray(new Foo[x.size()]);