Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert Arraylist<Float> to float[]

How I can do that?

I have an arraylist, with float elements. (Arraylist <Float>)

(float[]) Floats_arraylist.toArray() 

it is not working.

cannot cast from Object[] to float[]

like image 759
lacas Avatar asked Jan 29 '11 15:01

lacas


People also ask

Can ArrayList hold float?

You can't. A list of Float can only, logically, contain Floats.


1 Answers

Loop over it yourself.

List<Float> floatList = getItSomehow(); float[] floatArray = new float[floatList.size()]; int i = 0;  for (Float f : floatList) {     floatArray[i++] = (f != null ? f : Float.NaN); // Or whatever default you want. } 

The nullcheck is mandatory to avoid NullPointerException because a Float (an object) can be null while a float (a primitive) cannot be null at all.

In case you're on Java 8 already and it's no problem to end up with double[] instead of float[], consider Stream#mapToDouble() (no there's no such method as mapToFloat()).

List<Float> floatList = getItSomehow(); double[] doubleArray = floatList.stream()     .mapToDouble(f -> f != null ? f : Float.NaN) // Or whatever default you want.     .toArray(); 
like image 119
BalusC Avatar answered Sep 22 '22 09:09

BalusC