4

FloatBuffer has the method capacity() which tells us the maximum capacity of the FloatBuffer. However, it does not tell us how many elements are in that buffer. So how can I determine the number of elements in a FloatBuffer? I am trying to determine if my FloatBuffer is full or partially full.

4 Answers4

8

I can never keep the NIO buffer's straight in my head, but remaining() might be what you're after...

Returns the number of elements between the current position and the limit.

(Or just use hasRemaining() if you're after a simple Boolean...)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I'm getting `0` for remaining() so I must be doing something wrong. I know there is data in there. –  Aug 29 '11 at 20:35
  • 1
    @Code Monkey: Have you called `flip()` after writing? Please post a short but complete program demonstrating the problem... – Jon Skeet Aug 29 '11 at 20:36
  • Flip was it. Thanks. Called flip() after put() then checked remaining(). –  Aug 29 '11 at 20:38
  • Depending on what you're doing `flip()` may not be what you're after, since it resets the limit to the current position. You should look at `rewind`, though without further information everything's possible (maybe it's just `limit()` or even `position()`) – Voo Aug 29 '11 at 21:56
2

You can't. As with an array of floats you can get the length but which ones have been set is determined by the application.

Tim Niblett
  • 1,187
  • 7
  • 8
0

For debugging purpose just use

floatBuffer.toString()

At the end of the string the informations about the current position and the capacity will be shown, like

...[pos=0 lim=1024 cap=1024]

YBrush
  • 310
  • 1
  • 10
0

So how can I determine the number of elements in a FloatBuffer?

Wouldn't it just be the position() ?

To determine if you can write more to it, just test for fb.remaining() > 0 or fb.hasRemaining().

Jord Sonneveld
  • 456
  • 2
  • 4