10

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!

3 Answers3

12

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.

Rahul
  • 15,979
  • 4
  • 42
  • 63
2

Have you tried

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

i.e use the class Double and not the primitive type 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.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • @Telthien in that case could you redefine the list as `List` – Karthik T Jan 03 '13 at 07:17
  • @Telthien or you could use [ArrayUtils](http://stackoverflow.com/questions/3770289/converting-array-of-primitives-to-array-of-containers-in-java) as shown in the link to convert from `Double[]` to `double[]` – Karthik T Jan 03 '13 at 07:18
1

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[] d = new Double[out.size()];
out.toArray(d);
double[] d1 = ArrayUtils.toPrimitive(d);
Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
Avinash T.
  • 2,280
  • 2
  • 16
  • 23