user2440550
user2440550

Reputation: 39

How to get a array[] out of my LinkedList

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.

Upvotes: 3

Views: 97

Answers (3)

Andy Thomas
Andy Thomas

Reputation: 86449

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

Upvotes: 3

Jesse Craig
Jesse Craig

Reputation: 560

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

Upvotes: 1

Michal Borek
Michal Borek

Reputation: 4624

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

Upvotes: 3

Related Questions