Pawan
Pawan

Reputation: 32321

How to convert an Object[] type to Userdefined array type

I am creating the Leg Objects this way

List<Leg> legs = new ArrayList<Leg>(legdata.length);

I need to pass this legs to an method with the below signature as shown :

 public static String getStrategy(Leg[] leg)

when i did the below way i am getting an error .

String resultData = CMPUtil.getStrategy(legs.toArray());

Also tried this way

Leg les[] = (Leg)legs.toArray();  ( It says cannot cast from Object to Leg)

could anybody please let me know , how to resolve this ??

Upvotes: 0

Views: 1140

Answers (3)

holymoly
holymoly

Reputation: 11

Leg les[] = legs.toArray(new Leg[legs.length]);

Upvotes: 1

Erhan Bagdemir
Erhan Bagdemir

Reputation: 5327

try

String resultData = CMPUtil.getStrategy((Leg [])legs.toArray(new Leg[legs.size()]));

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500785

Pass in an array of the right type to the other overload of List.toArray:

Leg[] legsArray = legs.toArray(new Leg[0]); // Or new Leg[legs.size()]

Upvotes: 2

Related Questions