| Author |
Call to Collection.toArray() can be optimized? How?
|
Darien Cheung
Ranch Hand
Joined: Aug 13, 2004
Posts: 36
|
|
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[0])) (basically convert the arraylist into an object array of OperationException Thanks for any help you can provide!
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24051
|
|
Hi Darien, Welcome to JavaRanch! 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 (OperationException[])errorList.toArray(new OperationException[errorList.size()])) Then toArray doesn't need to allocate a new array at all. This is a sufficiently common idiom that the Eclipse IDE will do this exact expansion for a macro named "toArray".
|
[Jess in Action][AskingGoodQuestions]
|
 |
 |
|
|
subject: Call to Collection.toArray() can be optimized? How?
|
|
|