y********o 发帖数: 2565 | 1 At the very bottom of the following page:
http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.ht
ml
Suppose that c is known to contain only strings (perhaps because c is of typ
e Collection). The following snippet dumps the contents of c into a
newly allocated array of String whose length is identical to the number of e
lements in c.
String[] a = c.toArray(new String[0]);
The API doc for public T[] toArray(T[] a) says:
|
g*****g 发帖数: 34805 | 2 don't make much difference, new String[5] is an array too.
typ
a
e
【在 y********o 的大作中提到】 : At the very bottom of the following page: : http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.ht : ml : : Suppose that c is known to contain only strings (perhaps because c is of typ : e Collection). The following snippet dumps the contents of c into a : newly allocated array of String whose length is identical to the number of e : lements in c. : String[] a = c.toArray(new String[0]); :
|
y********o 发帖数: 2565 | 3 Thx, I was just curious about the capacity of the array at initialization.
It makes no difference if a.length <= c.size(), otherwise, you get null for
a[i] where i>c.size().
【在 g*****g 的大作中提到】 : don't make much difference, new String[5] is an array too. : : typ : a : e
|
m******t 发帖数: 2416 | 4 String[] a = c.toArray(new String[c.size()]);
is what I usually do.
for
【在 y********o 的大作中提到】 : Thx, I was just curious about the capacity of the array at initialization. : It makes no difference if a.length <= c.size(), otherwise, you get null for : a[i] where i>c.size().
|
o******t 发帖数: 1144 | 5 but it is runtime too, right? I guess this String[0] is just a hint on type
【在 m******t 的大作中提到】 : String[] a = c.toArray(new String[c.size()]); : is what I usually do. : : : for
|
m******t 发帖数: 2416 | 6
type
The idea is to make an array big enough that can be used for both a hint on
type and the actual container returned.
【在 o******t 的大作中提到】 : but it is runtime too, right? I guess this String[0] is just a hint on type
|