Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple StringBuilder constructor/method issue

Tags:

java

I got a StringIndexOutOfBoundsException for setCharAt(int index, char ch):

StringBuilder word = new StringBuilder(4);

for(int i = 0; i < 4; i++)
    word.setCharAt(i,'-');

StringBuilder(int capacity): Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.

setCharAt(int index, char ch): The character at the specified index is set to ch.

The only thing I can think of is that no memory was allocated, but then what's the point of StringBuilder(int capacity)?

like image 255
Steve P. Avatar asked Jun 08 '13 00:06

Steve P.


1 Answers

Just use StringBuilder.append()

The constructor you're using does nothing to put data in the StringBuilder.

It only specifies a practical size for the StringBuilder (which I believe is for performance).

Until you actually put stuff in the StringBuilder, your code will throw Exceptions.

Note that the documentation you've quoted says this explicitly:

"Constructs a string builder with NO CHARACTERS in it..."

like image 193
jahroy Avatar answered Oct 29 '22 07:10

jahroy