eclipse 从 ArrayList 转换为 double[] 时出错?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14134527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error converting from ArrayList to double[]?
提问by Rahul
I have an ArrayList
called out
, and I need to convert it to a double[]
. The examples I've found online have said two things:
我有一个ArrayList
电话out
,我需要将其转换为double[]
. 我在网上找到的例子说了两件事:
First, try:
第一次尝试:
double[] d = new double[out.size()];
out.toArray(d);
However, this produces the error (eclipse):
但是,这会产生错误(eclipse):
The method toArray(T[]) in the type List<Double> is not applicable for the arguments (double[]).
The second solution I found was on StackOverflow, and was:
我找到的第二个解决方案是在 StackOverflow 上,它是:
double[] dx = Arrays.copyOf(out.toArray(), out.toArray().length, double[].class);
However, this produces the error:
但是,这会产生错误:
The method copyOf(U[], int, Class<? extends T[]>) in the type Arrays is not applicable for the arguments (Object[], int, Class<double[]>)
What is causing these errors, and how do I convert out
to double[]
without creating these problems? out
indeed holds only double values.
是什么导致了这些错误,以及如何out
在double[]
不产生这些问题的情况下转换为?out
确实只有双重价值。
Thanks!
谢谢!
回答by Rahul
I think you are trying to convert ArrayList
containing Double
objects to primitive double[]
我认为您正在尝试将ArrayList
包含Double
对象转换为原始对象double[]
public static double[] convertDoubles(List<Double> doubles)
{
double[] ret = new double[doubles.size()];
Iterator<Double> iterator = doubles.iterator();
int i = 0;
while(iterator.hasNext())
{
ret[i] = iterator.next();
i++;
}
return ret;
}
ALternately, Apache Commons has a ArrayUtils
class, which has a method toPrimitive()
或者,Apache Commons 有一个ArrayUtils
类,它有一个方法toPrimitive()
ArrayUtils.toPrimitive(out.toArray(new Double[out.size()]));
but i feel it is pretty easy to do this by yourself as shown above instead of using external libraries.
但我觉得自己做这件事很容易,如上所示,而不是使用外部库。
回答by Karthik T
Have you tried
你有没有尝试过
Double[] d = new Double[out.size()];
out.toArray(d);
i.e use the class Double
and not the primitive type double
即使用类Double
而不是原始类型double
The error messages seem to imply that this is the issue. After all, since Double
is a wrapper class around the primitive type double
it is essentially a different type, and compiler will treat it as such.
错误消息似乎暗示这是问题所在。毕竟,由于Double
是原始类型的包装类,double
它本质上是一种不同的类型,编译器会这样对待它。
回答by Avinash T.
Generics does not work with primitive types that's why you are getting an error. Use Double array
instead of primitive double
. Try this -
泛型不适用于原始类型,这就是您收到错误的原因。使用Double array
代替primitive double
。尝试这个 -
Double[] d = new Double[out.size()];
out.toArray(d);
double[] d1 = ArrayUtils.toPrimitive(d);