从 ArrayList 转换为 double[] 时出错? [英] Error converting from ArrayList to double[]?

查看:46
本文介绍了从 ArrayList 转换为 double[] 时出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 outArrayList,我需要将它转换为 double[].我在网上找到的例子说了两件事:

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:

首先,尝试:

double[] d = new double[out.size()];
out.toArray(d);

然而,这会产生错误(eclipse):

However, this produces the error (eclipse):

The method toArray(T[]) in the type List<Double> is not applicable for the arguments (double[]).

我在 StackOverflow 上找到的第二个解决方案是:

The second solution I found was on StackOverflow, and was:

double[] dx = Arrays.copyOf(out.toArray(), out.toArray().length, double[].class);

然而,这会产生错误:

The method copyOf(U[], int, Class<? extends T[]>) in the type Arrays is not applicable for the arguments (Object[], int, Class<double[]>)

是什么导致了这些错误,我如何将 out 转换为 double[] 而不产生这些问题?out 确实只包含双精度值.

What is causing these errors, and how do I convert out to double[] without creating these problems? out indeed holds only double values.

谢谢!

推荐答案

我认为您正在尝试将包含 Double 对象的 ArrayList 转换为原始 double[]

I think you are trying to convert ArrayList containing Double objects to primitive 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;
}

或者,Apache Commons 有一个 ArrayUtils 类,它有一个方法 toPrimitive()

ALternately, Apache Commons has a ArrayUtils class, which has a method 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.

这篇关于从 ArrayList 转换为 double[] 时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆