File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toArray performance

 
Rob Acraman
Ranch Hand
Posts: 89
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Thanks,
Rob
 
Norm Radder
Ranch Hand
Posts: 707
3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 89
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Norm,
Now, why didn't I think of that ?!

Results show that it's cloned.
 
David Weitzman
Ranch Hand
Posts: 1365
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another good idea typically is to simply look at the source code that is provided with the JDK.
 
steve souza
Ranch Hand
Posts: 862
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

http://ssouza.kgbinternet.com/fdsapi/JAMonAdmin.jsp?sortCol=2&sortOrder=desc
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic