Search code examples
javamemory-managementstructmemcpy

Copy a list of structs to a float array in Java


In c++, if I have a struct with 3 floats:

 struct Vertex  
  {  
    float x;  
    float y;  
    float z;  
  }

If I have a list of these (std::vector<Vertex>) I'm able to copy them into a float[] by using memcpy like this:

float [] vertexBuffer = new float[m_vertices.size() * 3];  
memcpy(m_vertexBuffer, m_vertices.data(), m_vertices.size() * sizeof(Vertex));

Is there any equivalent way for me to do the same in Java? If I have a Java class VertexJava with floats for x,y,z, and these are all stored in an ArrayList, is there any way for me to copy all of their values into a float[] without iterating over all the items in the list?


Solution

  • Your collection e.g. List<Float> doesn't have float primitives, it has Float objects so you can't.

    Perhaps you could use a TFloatArrayList or a float[] from the start avoiding the need to create Float objects in the first place.