3

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.

4 Answers 4

5

You have a version of toArray that takes a type

toArray(T[] a)

So you would do:

myList.toArray(new CompositeType[myList.size()]);
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

size is a method. You have missed method paranthesis
0

The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.

CustomType[] array = myList.toArray(new CustomType[list.size()]);

Comments

0

Your myArr is an Array of CustomType, you cannot cast a CustomType object to a CustomType Array object. Do this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.