Search code examples
javafloatbuffer

Creation of FloatBuffer Array with for ¿overwrites values?


I'm creating an array of FloatBuffers with a for loop like this:

FloatBuffer[] buffer = new FloatBuffer[sizebuffer];

float[] farray = new float[sizeArray];

for(int i=0;i<sizebuffer;i++){
    for(int j=0;j<sizeArray;j++){

     farray[j]= I get the float values from other buffer....
    }

    buffer[i]= FloatBuffer.wrap(farray);  (*)

}

But for some reason it's changing the values on each row of the FloatBuffer array ("buffer") each time this line (*) is executed. For example, after buffer[0] is given its value, I printed buffer[0].get(0), then after buffer[1] was given its values, I printed buffer[0].get(0) again, but the value had been changed. It's coping the values for each new buffer[i] on each of the previous ones buffer[0], buffer[1]... I don't understand why is this happening?


Solution

  • The FloatBuffer.wrap method effectively retains the array passed to it. So all your buffers will end up with whatever values you last process in the for loop. A simple, but relatively expensive way of avoiding this problem would be to System.arraycopy the array before wrapping it in each buffer.

    To be honest, you should just use one of the put family of methods to set the float values into the buffers while you are reading them from your external source.

    for(int i=0;i<sizebuffer;i++){
        for(int j=0;j<sizeArray;j++){
            farray[j]= some value from other buffer....
        }
    
        buffer[i]= FloatBuffer.allocate(farray.length);
        buffer[i].put(farray);
    }