wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes toArray method of List Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "toArray method of List" Watch "toArray method of List" New topic
Author

toArray method of List

joshua antony
Ranch Hand

Joined: Jun 05, 2006
Posts: 117


Running the above code I get the following output:

length... 4
a
b
c
d

Which object does a refer to ?. My guess is that it referes to the object referred by test.But if so, the size of test array is only 2 that we have specified during its creation, so how come 4...
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.

How to use the toArray() method of Collection?
[ November 01, 2006: Message edited by: wise owen ]
joshua antony
Ranch Hand

Joined: Jun 05, 2006
Posts: 117
Thank you Wise,

Regards,
Joshua
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi ranchers,
if the array named test is larger than the list, the elements at the "right end" are filled up with default values. Both in the dummy "test" and in the "real used" array named a.





Gives:
a length... 6
a
b
c
d
null
null
test length...6
a
b
c
d
null
null
The list: [a, b, c, d]




I like it more to use toArray with a dummy array of size zero to prevent this. Also checking the size of the list in advance is not necessary then.
eg: String[] strArray = list.toArray(new String[0]);


Yours,
Bu.


all events occur in real time
 
GeeCON Prague 2014
 
subject: toArray method of List