Procrastiblog

November 16, 2008

A CharBuffer is Not a StringBuffer, or Something You Already Knew If You Read the Documentation

Filed under: Tech — Chris @ 3:46 pm

A Java CharBuffer doesn’t behave the way I would expect.

CharBuffer buf = CharBuffer.allocate(8).put("foo");
System.out.println( "'" + buf + "'" );

yields

'^@^@^@^@^@'

or

'

This is because a CharBuffer is not a StringBuffer: toString() gives you everything from the current “position” to the end of the buffer. I.e., what you haven’t written yet. (Those funny symbols, or the lack thereof, are nulls.) Instead you want

CharBuffer buf = CharBuffer.allocate(8).put("foo");
System.out.println( "'" + buf.flip() + "'" );

which yields

'foo'

flip() makes the current view of the buffer what has been written to it so far.

P.S. Why can’t flip() return a CharBuffer, so that

Create a free website or blog at WordPress.com.

%d bloggers like this: