why it's NOT safe to replace a StringBuffer object with a StringBuilder in java version earlier than 1.5

StackOverflow https://stackoverflow.com/questions/15844328

Frage

Good evening, i read these statement in a blog it's NOT safe to replace a StringBuffer object with a StringBuilder in java version earlier than 1.5 and it seems to be a fact, but there's no apparent reason for that !!, i know that StringBuffer is extending class java.lang.AbstractStringBuilder. StringBuilder also extends AbstractStringBuilder, so it inherits those methods as well.so from the compiler's point of view you can safely replace StringBuffer with StringBuilder. Of course StringBuilder is not synchronized, so if you care about synchronization you can't replace string buffer with string builder so in my point of view synchronization is the only factor that we could think of when replacing string buffer with string builder, but it seems that there's another factor JAVA Version but i don't know how these effects the decision, please discuss these point to me.

War es hilfreich?

Lösung

The reason it's not safe to use it in a VM before 1.5 is because StringBuilder just didn't exist before 1.5. If you look at the JavaDoc for StringBuilder you can see it has only exited since 1.5.

Regarding when to use it in 1.5+, you are mostly safe in just substituting StringBuffer out in favor of StringBuilder. The case when you wouldn't want to do this is if you have more than one thread writing to the buffer. However, in most cases when you just want to make a String and return it, from a toString() method, for instance, you should be safe.

Andere Tipps

See http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

StringBuilder didn't exist before Java 1.5, so earlier Java versions wouldn't be able to use it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top