从错误的ArrayList转换为加倍[]? [英] Error converting from ArrayList to double[]?

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

问题描述

我有一个的ArrayList 名为退出,我需要将其转换为一个双[] 。我在网上找到的例子已经说了两句话:

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);

不过,这会产生错误(日食):

However, this produces the error (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:

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.

谢谢!

推荐答案

我认为你正试图转换的ArrayList 包含双击对象的原始双[]

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的百科全书有一个 ArrayUtils 类,它有一个方法 toPrimitive()

 ArrayUtils.toPrimitive(out.toArray(new Double[out.size()]));

但我觉得这是pretty容易自己做到这一点,如上图所示,而不是使用外部库。

but i feel it is pretty easy to do this by yourself as shown above instead of using external libraries.

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

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