3

I need to convert my List:

List<Double> listFoo = new LinkedList<Double>();

to a array of double. So I tried:

double[] foo = listFoo.toArray();

But I get the error:

Type mismatch: cannot convert from Object[] to double[]

How can I avoid this? I could Iterate over the list and create the array step by step, but I don't want to do it this way.

chuff
  • 5,846
  • 1
  • 21
  • 26

3 Answers3

3

You can't make the array of primitives with the standard List class's toArray() methods. The best you can do is to make a Double[] with the generic method toArray( T[] ).

Double[] foo = listFoo.toArray( new Double[ listFoo.size() ] ); 

One easy way to make a double[] is to use Guava's Doubles class.

double[] foo = Doubles.toArray( listFoo );
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
3

You need to make, generic one

Double[] foo = listFoo.toArray(new Double[listFoo.size()]);

That would be the fastest way.

Using new Double[listFoo.size()] (with array size) you will reuse that object (generally it is used to make generic invocation of method toArray).

Michal Borek
  • 4,584
  • 2
  • 30
  • 40
1

It should work if you make foo an array of Doubles instead of doubles (one is a class, the other a primitive type).

Jesse Craig
  • 560
  • 5
  • 18