StringBuffer and StringBuilder

时间:2022-01-01 00:59:10

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

所以, StringBuilder是在JDK5中引进的StringBuffer非线程安全版, 但是功能一样, 且性能更好 --> 在不太严格的测试中, 速度是后者的3倍.

对StringBuffer/StringBuilder中内容的修改可以通过setCharAt(), replace(), deleteCharAt(), insert()这些方法来实现

StringBuffer sb = new StringBuffer("teststr");
sb.setCharAt(4, 'S');
sb.append("ing");
assert sb.toString().equals("testString"); StringBuffer sb = new StringBuffer("teststr");
sb.replace(4, sb.length(), "String");
assert sb.toString().equals("testString"); StringBuffer sb = new StringBuffer("teststr");
sb.deleteCharAt(4);
sb.insert(4, 'S');
sb.append("ing");
assert sb.toString().equals("testString");