Error converting from ArrayList to double []?

I have an ArrayList called out , and I need to convert it to double[] . The examples I found on the Internet said two things:

First try:

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

However, this causes an error (eclipse):

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

The second solution I found was in StackOverflow and was:

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

However, this causes an error:

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

What causes these errors and how to convert out to double[] without creating these problems? out really only contains double values.

Thanks!

+8
java arraylist arrays list eclipse
source share
3 answers

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

ALTERally, Apache Commons has an ArrayUtils class that has a toPrimitive() method

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

but I feel that it’s pretty simple to do as shown above, instead of using external libraries.

+12
source share

You tried

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

use the Double class, not the primitive Double type

Error messages seem to imply that this is a problem. In the end, since Double is a wrapper class around the primitive type Double , it is essentially a different type, and the compiler will consider it as such.

+2
source share

Generics does not work with primitive types, so you get an error. Use a Double array instead of a primitive double . Try it -

 Double[] d = new Double[out.size()]; out.toArray(d); double[] d1 = ArrayUtils.toPrimitive(d); 
+1
source share

All Articles