Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call String subSequence() after convert Stringbuffer toString()

I found in a existing Java program code the following snip:

StringBuffer b = new Stringbuffer()
// fill the StringBuffer
(...)

String temp = b.toString();
return temp.subSequence(0, b.toString().length() - 1);

I don't understand why they done a subSequence from position 0 to the end...
Is the format of a StringBuilder after the convertition into a String that ugly?

They, they wrote this code aren't in my company anymore, so I can't ask them...

Hope you guys can help me out.


1 Answers

The idea is to strip one char from the end, note that all Java standard library classes follow a convention about start / end index parameters, star is inclusive and end is exclusive. Also I agree that the code is ugly, it should be

...
return b.subSequence(0, b.length() - 1);

it's shorter and also more efficient. Also StringBuffer is a legacy class you can replace it with faster StringBuilder

like image 52
Evgeniy Dorofeev Avatar answered Jun 11 '26 11:06

Evgeniy Dorofeev