AndreaNobili
AndreaNobili

Reputation: 42957

Can I initialize a Java array with another collection?

I am working on a Java class that contains this field:

private com.enel.xmlns.EDILM.SalReport.SalDettaglio[] sal;

this is an array. Is it possibile initizialize this sal object with some other collection (a list) type in some way?

Tnx

Upvotes: 1

Views: 197

Answers (3)

Loïc Gammaitoni
Loïc Gammaitoni

Reputation: 4171

You might notice if you have a quick look at the Collecion javadoc that collections are supposed to implement a toArray method.

So yes, you can at anytime initialize an Array variable using the array returned by the toArray method of your collection. (but you'll have to pay attention that the generic type of your collection correpond to the type of your array variable, and might have to cast what the toArray methods return to fit the type of your variable).

You would thus write something like :

YourType[] sal= yourCollection.toArray(new YourType[0]);

Upvotes: 2

Predrag Maric
Predrag Maric

Reputation: 24423

Would this work for you?

sal = myCollection.toArray(new com.enel.xmlns.EDILM.SalReport.SalDettaglio[myCollection.size()])

Upvotes: 0

A4L
A4L

Reputation: 17595

If you have a List then you can use T[] toArray(T[] a)

Upvotes: 0

Related Questions