转换一个ArrayList对象数组 [英] Convert an ArrayList to an object array
问题描述
有没有在Java中转换一个ArrayList成对象数组的命令。我知道如何做到这一点从复制ArrayList中到对象数组中的每个对象,但我不知道是否会是自动完成。
我想是这样的:
的ArrayList<&类型A GT;一个;//让我们想象一下一个充满了类型A的对象类型A []数组= MagicalCommand(一);
有点像标准的<一个href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html#toArray%28T%5b%5d%29\">Collection.toArray(T[])应该做你所需要的(注意,的ArrayList
工具收藏
)
类型A []数组= a.toArray(新类型A [a.size()]);
在一个侧面说明,你应该考虑定义 A
为类型列表与LT;类型A&GT;
,而不是的ArrayList&LT;类型A方式&gt;
,这避免了一些实施的具体定义,未必真的是适用于您的应用程序
此外,请参阅<一个href=\"http://stackoverflow.com/questions/174093/toarraynew-myclass0-or-toarraynew-myclassmylist-size/174146#174146\">this问题关于使用 a.size()
而不是 0
作为数组的大小通过到 a.toArray(类型A [])
Is there a command in java for conversion of an ArrayList into a object array. I know how to do this copying each object from the arrayList into the object array, but I was wondering if would it be done automatically.
I want something like this:
ArrayList<TypeA> a;
// Let's imagine "a" was filled with TypeA objects
TypeA[] array = MagicalCommand(a);
Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList
implements Collection
):
TypeA[] array = a.toArray(new TypeA[a.size()]);
On a side note, you should consider defining a
to be of type List<TypeA>
rather than ArrayList<TypeA>
, this avoid some implementation specific definition that may not really be applicable for your application.
Also, please see this question about the use of a.size()
instead of 0
as the size of the array passed to a.toArray(TypeA[])
这篇关于转换一个ArrayList对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!