This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes toArray method in Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "toArray method in Collection" Watch "toArray method in Collection" New topic
Author

toArray method in Collection

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 8795

Guys,

The following line,

String arr[] = list.toArray(new String[0]). Assuming that list is an ArrayList of String that has One, Two, Three, Four as it's elements. Now what does new String[0] signify?? Does it refer only to the first element in the ArrayList "One"??


SCJP 1.4, SCWCD 1.4 - Hints for you, SCBCD Hints - Demnachst, SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

"new String[0]" creates a new array of type string that can hold 0 elements. There is already a discussion around here somewhere about why that can be useful, but Collection.toArray is where it is used quite often just to get the return type correctly.

Please note that "new String[list.size()]" will be a bit more efficient; with 0 you'll create two arrays (one yourself and one in toArray). With list.size() the array is big enough to hold all of the values and will therefore be reused.


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 8795

Thanks Rob. But when I declare a String array of size 1, how will I store all the elements of my List into that String array? The other alternative that you suggested list.size() is reasonable for me to understand.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

According to the API, if the array is not large enough to store all the elements, a new array will be created of the same type that will be large enough.

That's also why the method returns an array - it may be different from the array passes as a parameter. It doesn't have to be though.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: toArray method in Collection
 
Similar Threads
Default Object and String sizes?
Eliminating Duplicate in Arraylist and moving the dups to another arraylist.
Casting problem of Arraylist
reference variable
ArrayList objects