2012-10-08 67 views
1

所以想象我有以下几种:myList类型ArrayList<CustomType>我想将其转换为数组,我该怎么做呢?ArrayList <>。values.toArray,转换为自定义类型数组

我已经试过

CustomType[] myArr = (CustomType)myList.toArray(); 

这编译,没有问题,但我在运行时得到一个铸件例外。我目前的解决方案是遍历ArrayList并将每个条目写入数组,这并不好。

有什么想法?谢谢。

回答

3

你有一个版本指定者的,需要一个类型

toArray(T[] a)

所以,你会怎么做:

myList.toArray(new CompositeType[myList.size()]); 
0

不传递任何参数的toArray()方法返回Object []。所以你必须传递一个数组作为参数,这个参数将被列表中的数据填充并返回。您也可以传递一个空数组,但您也可以传递所需大小的数组。 (CustomType [list.size()]);我们可以通过下面的方法来创建自定义类型的数组:myList.toArray(new CustomType [list.size()]);

1

myList.toArray(新CustomType [myList.size]);

+0

大小是一种方法。你错过了方法paranthesis – exexzian

0

您的myArr是CustomType数组,您不能将CustomType对象转换为CustomType数组对象。这样做:

CustomType[] myArr = (CustomType[])myList.toArray(); 
相关问题