开发者

Standard Place for an Empty String Array in the JDK

开发者 https://www.devze.com 2022-12-23 14:16 出处:网络
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 开发者_如何学JAVACollection (e.g. ArrayList)to a String Array I find my

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 开发者_如何学JAVACollection (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


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.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号