Call to Collection.toArray() can be optimized? How?
Joined: Aug 13, 2004
I'm using PMD to analyze my code and one of the comments I get is:
Call to Collection.toArray() may be optimizable
In what way can it be optimizable? For example, I have lines of code that look like:
Array errorList = new ArrayList(); ... do stuff and errorList.add(object); ... and then at the end I do (OperationException)errorList.toArray(new OperationException)) (basically convert the arraylist into an object array of OperationException
Thanks for any help you can provide!
author and iconoclast
I've only taken a quick look at PMD, so I can't say for sure what it means, but I'd guess the following:
You're constructing a zero-length array here. The toArray method is going to turn around and allocate a finite-sized array of this same type, because the zero-length one probably won't hold the errorList, right? But if you pass in an array of just the right size, toArray will actually use it. Therefore, the most efficient way to do this looks like