Reputation: 8944
Is there a way to use the toArray()
method on an ArrayList<CustomObject>
?
From what I see, it can only be used with Object
Upvotes: 2
Views: 7469
Reputation: 271
CustomObj[] customArray = new CustomObj[size];
customArray = (CustomObj[])ArrayListObj.toArray(customArray);
Upvotes: 0
Reputation: 38132
Use:
CustomObject[] customObjects = myList.toArray(new CustomObject[myList.size()])
Upvotes: 1
Reputation: 77034
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()]);
Upvotes: 18