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

The Silver is the New Black Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: