JDK 中空字符串数组的标准位置

发布于 2024-08-26 06:42:54 字数 472 浏览 2 评论 0原文

你好,JDK 中有一个访问空数组常量的标准位置吗? 1.5.

当我想要从字符串集合(例如 ArrayList)到字符串数组的转换时,我发现自己使用自己的 这是在我自己的 Constants 类中定义的:

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

然后在我的客户端代码中类似:

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

我想知道这是否是“惯用”的做法,或者我是否遗漏了一些东西 我从我所做的简短搜索中得到的印象是,这种事情在很多人的代码中都很普遍。

任何想法、答案、评论(除了我不应该真正使用字符串数组)都非常感谢,

干杯 西蒙

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月亮邮递员 2024-09-02 06:42:54

我建议进行以下代码改进:

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

这样,toArray 方法使用提供的、适当大小的数组作为容器,而不是在幕后创建一个新数组。来自 ArrayList javadoc :

如果列表适合指定的范围
数组,它在其中返回。
否则,分配一个新数组
具有指定的运行时类型
数组和该列表的大小。

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.

喜爱皱眉﹌ 2024-09-02 06:42:54

JDK 中没有类似的数组定义。在 JDK 中执行此操作的唯一两种标准方法是您列出的或

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

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文