| 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.
|
 |
 |
|
|
subject: toArray method in Collection
|
|
|