2

Is there a way to use the toArray() method on an ArrayList<CustomObject>?

From what I see, it can only be used with Object

1
  • 1
    There is ArrayList<T>.toArray()... Commented Nov 16, 2011 at 0:58

3 Answers 3

18

You need to pass in an array of CustomObject in order to get one back. The parameter-free ArrayList.toArray() call returns an Object[], but the parameterized version T[] ArrayList<T>.toArray(T[]) returns what you expect. If you size the array you pass as a parameter correctly then the call will use the array you pass rather than allocate another one, e.g.

ArrayList<CustomObject> foo;
//...
CustomObject[] bar = foo.toArray(new CustomObject[foo.size()]);
1

Use:

CustomObject[] customObjects = myList.toArray(new CustomObject[myList.size()])
0

CustomObj[] customArray = new CustomObj[size];

customArray = (CustomObj[])ArrayListObj.toArray(customArray);

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.