51

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[]

bestsss
  • 11,796
  • 3
  • 53
  • 63
lacas
  • 13,928
  • 30
  • 109
  • 183
  • 1
    The inverse of this: http://stackoverflow.com/questions/2585907/is-there-a-native-java-method-to-box-an-array – Seva Alekseyev Jan 29 '11 at 15:09
  • `int s=list.size(); float[] a = new float[s]; for (int i=0;i – bestsss Jan 29 '11 at 15:11
  • Different primitive type, but essentially the same question: [Creating a byte\[\] from a List](http://stackoverflow.com/questions/1565483/creating-a-byte-from-a-listbyte) – finnw Feb 01 '11 at 20:51

3 Answers3

43

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();
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
36

You can use Apache Commons ArrayUtils.toPrimitive():

List<Float> list = new ArrayList<Float>();
float[] floatArray = ArrayUtils.toPrimitive(list.toArray(new Float[0]), 0.0F);
dogbane
  • 266,786
  • 75
  • 396
  • 414
5

Apache Commons Lang to the rescue.

Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408