File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Performance and the fly likes toArray performance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "toArray performance" Watch "toArray performance" New topic

toArray performance

Rob Acraman
Ranch Hand

Joined: Dec 03, 2000
Posts: 89
Hi All,

Just a question I've been pondering ....

If I have a big ArrayList, and call toArray() on it, will it simply return me a reference to a pre-existing private array, or will it construct a whole new array object?

Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 692
Why don't you write a test program to see what happens?
Store into the new array and see if the old one is changed.
IE does the new array reference refer to the old one? Or has it been cloned?
Rob Acraman
Ranch Hand

Joined: Dec 03, 2000
Posts: 89
Thanks Norm,
Now, why didn't I think of that ?!

Results show that it's cloned.
David Weitzman
Ranch Hand

Joined: Jul 27, 2001
Posts: 1365
The first place to look when you have a question like this is the Java API documentation. In this case the javadocs explain that a new array is allocated and returned.
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
Another good idea typically is to simply look at the source code that is provided with the JDK.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
steve souza
Ranch Hand

Joined: Jun 26, 2002
Posts: 862
Keep in mind it probably always creates a 1 dimensional array to hold your elements, however it is a shallow copy of the elements themselves. Also, I have some code that converts a ResultSet to an ArrayList and then using toArray I convert the ArrayList to an Object[][]. I time this code with JAMon . It must be very efficient as it is one of the fastest pieces of code that I have performance stats for.

If you look at this report the line 'com.fdsapi.ResultSetUtils.listToObjectArray()' converts from the ArrayList to an array. - a fast, free open source performance tuning api.
JavaRanch Performance FAQ
I agree. Here's the link:
subject: toArray performance
It's not a secret anymore!