Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList<>.values.toArray, cast to a custom type array

Tags:

java

casting

So imagine I have the following: myList of type ArrayList<CustomType> and I want to convert it to an array, how would I go about this?

I have tried

CustomType[] myArr = (CustomType)myList.toArray();

This compile, no problem but I get a casting exception at runtime. My current solution is iterating through the ArrayList and writing each entry into the array, not good.

Any idea? Thanks.

like image 495
jim Avatar asked May 28 '26 10:05

jim


2 Answers

You have a version of toArray that takes a type

toArray(T[] a)

So you would do:

myList.toArray(new CompositeType[myList.size()]);
like image 107
Suraj Chandran Avatar answered May 31 '26 06:05

Suraj Chandran


myList.toArray(new CustomType[myList.size]);

like image 33
Strikegently Avatar answered May 31 '26 06:05

Strikegently



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!