aspose file tools
The moose likes Java in General and the fly likes Call to Collection.toArray() can be optimized?  How? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Call to Collection.toArray() can be optimized?  How?" Watch "Call to Collection.toArray() can be optimized?  How?" New topic
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
    
  13

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]
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Call to Collection.toArray() can be optimized? How?
 
Similar Threads
Adding 2-d ArrayList to JTable
ClassCastException in Tag Library
String[]
How to dinamically populate a String array?
Casting Object[] into String[]