铸造与发行ArrayList的toArray()方法 [英] Casting issue with ArrayList toArray() method
问题描述
在一个类我有构造函数如下:
In one class I have constructor which looks like:
Class(int x, int y, int[] moves);
在创造这些我都存储在ArrayList中移动对象的其他类。动作是数字。所以,当这个类决定TI创建新的对象,它必须首先转换此ArrayList到数组。所以,我想是这样的:
In other class which creates those objects I have moves stored in ArrayList. Moves are numbers. So when this class decides ti create new object it must first convert this ArrayList into array. So I tried something like this:
new Object(0, 0, (int[])moves.toArray(int[moves.size()]);
但它不工作。究竟应该如何正确完成?
But it doesn't work. How should it be done properly?
推荐答案
调用的结果的toArray()
上的的ArrayList
是从不的一个 INT []
。你不能有一个的ArrayList< INT>
在Java中,由于仿制药的方式工作。充其量这将是一个整数[]
,其中你再需要转换。请注意,即使你可以从整数
转换为 INT
,您的无法的投一个整数[]
到 INT []
。有些事情要遍历所有的值。
The result of calling toArray()
on an ArrayList
is never an int[]
. You can't have an ArrayList<int>
in Java due to the way generics works. At best it would be an Integer[]
, which you'd then need to convert. Note that even though you can convert from Integer
to int
, you can't cast an Integer[]
to an int[]
. Something has to loop over the values.
您可能只是做它直接:
int[] values = new int[moves.size()];
for (int i = 0; i < values.length; i++) {
values[i] = moves.get(i);
}
另外的可能的创建一个整数[]
,然后从转换 - 但为什么复制两次
Alternatively could create an Integer[]
and then convert from that - but why do the copying twice?
这篇关于铸造与发行ArrayList的toArray()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!