tags:

views:

53

answers:

2

Hi is there a standard place for accessing empty array constants in the JDK > 1.5.

When I want to do a conversion from a String Collection (e.g. ArrayList)to a String Array I find myself using my own which is defined in my own Constants class:

public static final String[] EMPTY_STRING_ARRAY = new String[0];

And then in my client code something like:

String[] retVal = myStringList.toArray(Constants.EMPTY_STRING_ARRAY);
return retVal;

I was wondering if this is the "idiomatic" way of doing it or if I'm missing something I get the impression from the brief search I did that this kind of thing is prevalent in many people's code.

Any ideas, answers, comment (aside from that I shouldn't really use String Arrays) greatly appreciated,

Cheers Simon

A: 

There are no array definitions like that in the JDK anywhere. The only two standard ways of doing it in the JDK are that which you list or

String ret[] = new String[myStringList.size()];
myStringList.toArray(ret);
return ret;
M. Jessup
+2  A: 

I would recommend the following code improvement :

String[] retval = myStringList.toArray(new String[myStringList.size()]);

This way, the toArray method uses the provided, appropriately-sized array as a container, instead of creating a new one behind the scenes. From the ArrayList javadoc :

If the list 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 list.

Olivier Croisier
I agree with your answer, but would point out that where the array is created is academic, since the example from the code is using a shared object. Therefore the call would not generate an extra Object (as opposed to the call ... = list.toArray(new String[0]), which I agree is inefficient).
M. Jessup
Hum, you're right. Thanks for pointing out !
Olivier Croisier
Thanks for your reply.I'm a little confused about why this is an improvement. So you're saying that it's better to write something explicitly in my code that emulates what would happen "behind the scenes" in the ArrayList, than just let it happen behind the scenes, with the possibility that in future releases of the JDK it may somehow (don't ask me how) be optimised?Is it simply because I'm directly allocating a new array rather than letting the ArrayList create one through some kind of reflective mechanism (which is slightly more efficient in modern jvms)?CheersSimon
Simon B