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

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

share|improve this question

1  
There is ArrayList<T>.toArray()... – Oli Charlesworth Nov 16 '11 at 0:58
feedback

3 Answers

up vote 7 down vote accepted

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()]);
share|improve this answer
feedback

Use:

CustomObject[] customObjects = myList.toArray(new CustomObject[myList.size()])
share|improve this answer
feedback

CustomObj[] customArray = new CustomObj[size];

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

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.