• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toArray method of List

 
joshua antony
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Wise,

Regards,
Joshua
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic