Aza*_*Aza 8 java eclipse arrays list arraylist
我有一个ArrayList
叫out
,我需要把它转换为double[]
.我在网上找到的例子说了两件事:
第一次尝试:
double[] d = new double[out.size()];
out.toArray(d);
Run Code Online (Sandbox Code Playgroud)
但是,这会产生错误(eclipse):
The method toArray(T[]) in the type List<Double> is not applicable for the arguments (double[]).
Run Code Online (Sandbox Code Playgroud)
我找到的第二个解决方案是在StackOverflow上,并且是:
double[] dx = Arrays.copyOf(out.toArray(), out.toArray().length, double[].class);
Run Code Online (Sandbox Code Playgroud)
但是,这会产生错误:
The method copyOf(U[], int, Class<? extends T[]>) in the type Arrays is not applicable for the arguments (Object[], int, Class<double[]>)
Run Code Online (Sandbox Code Playgroud)
是什么导致了这些错误,如何out
在double[]
不创建这些问题的情况下转换为?out
确实只有双重价值.
谢谢!
Rah*_*hul 12
我想你正在尝试将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;
}
Run Code Online (Sandbox Code Playgroud)
或者,Apache Commons有一个ArrayUtils
类,它有一个方法toPrimitive()
ArrayUtils.toPrimitive(out.toArray(new Double[out.size()]));
Run Code Online (Sandbox Code Playgroud)
但我觉得如上所示自己做这个很容易,而不是使用外部库.