1

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?

2 Answers2

1

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);
}
Perception
  • 79,279
  • 19
  • 185
  • 195
  • Thanks for the explanation! And you are completely right, I could have just used "put" directly: buffer[i].put(j, float value); Changed it and works perfectly. – Maria Garcia Mar 21 '13 at 18:57
0

This is what is stated in JavaDOC

public static FloatBuffer wrap(float[] array)

Wraps a float array into a buffer.

The new buffer will be backed by the given float array; that is, **modifications to the buffer will cause the array to be modified and vice versa.** The new buffer's capacity and limit will be array.length, its position will be zero, and its mark will be undefined. Its backing array will be the given array, and its array offset will be zero.

Parameters:
    array - The array that will back this buffer 
Returns:
    The new float buffer
Jabir
  • 2,776
  • 1
  • 22
  • 31