Emrakul Emrakul - 6 months ago 11
Java Question

Error converting from ArrayList to 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:

First, try:

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.

Thanks!

Answer

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

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.