The following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the number of elements in c: String a = (String) c.toArray(new String); Howcome the string array length is equal to the number of elements in c?
toArray public Object toArray(Object�a) Returns an array containing all of the elements in this collection whose runtime type is that of the specified array. 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. If this collection fits in the specified array with room to spare (i.e., the array has more elements than this collection), the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of this collection only if the caller knows that this collection does not contain any null elements.)
I bolded the part that pertains to your question.
Joined: Aug 29, 2001
So, initially the length of array is 0 (new String) and it can be extended as per requirement??? or Is it the length of array a mentioned? Can you explain little bit clear? [ June 06, 2002: Message edited by: Thiru Thangavelu ]
I thought the API stated it pretty clearly... but I'll try to clarify it some more:
The first line shows us (sorta) a collection of size 8. The second line creates a simple String Array of length = 0. As per the API, the 3rd line will return an array of type String (the same type as 'b'). The collection DOES NOT fit in the specified array, so it creates a NEW array of the same type (String) and of the size of the Collection (8), and returns that. So 'a' and 'b' will be references to two different array objects ... now if you had this code:
It would simply put the contents of the collection into the array 'b' because the size fits. And 'a' and 'b' will both reference the same array [ June 06, 2002: Message edited by: Jessica Sant ]
String b = new String; //creates array of length = 1
wouldn�t this create an array of length 0(zero) instead of length 1? Francisco
Francisco<br />SCJP<br />please use the [code][/code] tags when showing code.Click <a href="http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=ubb_code_page" target="_blank" rel="nofollow">here</a> to see an example.