How to create a floatbuffer dynamically

I need to create a FloatBuffer from a dynamic set of floats (that is, I don't know the length ahead of time). The only way I found this is rather inelegant (below). I assume that I am missing something and should have a cleaner / simpler method.

My decision:

Vector<Float> temp = new Vector<Float>();
//add stuff to temp
ByteBuffer bb = ByteBuffer.allocateDirect( work.size() * 4/*sizeof(float)*/ );
bb.order( ByteOrder.nativeOrder() );
FloatBuffer floatBuf = bb.asFloatBuffer();
for( Float f : work )
    floatBuf.put( f );
floatBuf.position(0);

I use my buffers for OpenGL commands, so I need to support them (i.e. the resulting FloatBuffer is not just temporary space).

+5
source share
2 answers

OpenGL API Java, , LWJGL . , , BufferUtils org.lwjgl. BufferUtils.createFloatBuffer() float array, , Vector, . , , , , . LWJGL OpenGL 3.2+ .

, .

+4

ByteBuffer, . ( , )

.

SocketChannel sc = ...
ByteBuffer bb = ByteBuffer.allocateDirect(32 * 1024).order(ByteOrder.LITTLE_ENDIAN);
for(int i = 0 ; i < 100000000; i++) {
   float f = i;
   // move to a checkFree(4) method.
   if (bb.remaining() < 4) {
       bb.flip();
       while(bb.remaining() > 0)
           sc.write(bb);
   }
   // end of method
   bb.putFloat(f);

}

.

: . , ByteBuffer.

+1

All Articles