将集合转换为数组的最简单方法? [英] The easiest way to transform collection to array?

查看:31
本文介绍了将集合转换为数组的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个 Collection.将其转换为 Foo[] 的最佳(在当前上下文中是 LoC 中最短的)方法是什么?允许使用任何知名库.

Suppose we have a Collection<Foo>. What is the best (shortest in LoC in current context) way to transform it to Foo[]? Any well-known libraries are allowed.

UPD:(本节还有一个案例;如果您认为值得为它创建另一个线程,请留下评论):如何将 Collection 转换为 Bar[] 其中 Bar 具有带有 1 个 Foo 类型参数的构造函数,即 public Bar(Foo foo){ ... } ?

UPD: (one more case in this section; leave comments if you think it's worth to create another thread for it): What about transforming Collection<Foo> to Bar[] where Bar has constructor with 1 parameter of type Foo i.e. public Bar(Foo foo){ ... } ?

推荐答案

其中 x 是集合:

Foo[] foos = x.toArray(new Foo[x.size()]);

这篇关于将集合转换为数组的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆