索引贴:http://www.mcbbs.net/thread-138969-1-1.html
这个也是之前讲字符串的时候没讲的一个
首先,我们要知道的是它和String一样,都是一个类,但不同的是String是一个静态类,可以直接赋值,但StringBuffer必须使用new关键字实例化.
如何去做如果你认真看完了主杆篇就不会有任何问题了,我这里只重点说一下关于StringBuffer的几个方法.
StringBuffer的追加
我们在String里讲过一个追加方法concat,这里将讲解一个StringBuffer的追加方法.
代码示例
- public class book {
-
- public static void main(String[] args)
- {
- StringBuffer a=new StringBuffer("我把教程看完了,");
- a.append("我能看懂mod制作教程了!!");
- a.append("我来给楼主评分~");
- System.out.println(a);
- }
- }
我把教程看完了,我能看懂mod制作教程了!!我来给楼主评分~
StringBuffer 插入
代码示例
- public class book {
-
- public static void main(String[] args)
- {
- StringBuffer a=new StringBuffer("我把教程看完了,我来给楼主评分~");
- a.insert(8,"我能看懂mod制作教程了!!");
- System.out.println(a);
- }
- }
输出结果和上面是一样的,有人能总结出上面的各个量的含义吗?
变量名.insert(int,添加的字符)
int是在第某位前面添加,值得注意的是,和前面的一样,是从0开始数位。
StringBuffer颠倒
代码示例
- public class book {
-
- public static void main(String[] args)
- {
- StringBuffer a=new StringBuffer("~分评主楼给来我!!了程教作制dom懂看能我,了完看程教把我");
- a.reverse();
- System.out.println(a);
- }
- }
StringBuilder
在该类的API中,是这么说的:
This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
由此我们可以知道,该类是兼容StringBuffer的api的,但是该类并不是线程安全的。所以,我们不应该有线程安全要求的情况下使用它,但是在其他情况下,我们都应该使用StringBuilder,因为它比StringBuffer快的多。
测试代码:
- public class MainTest {
- public static void main(String[] args) {
- long l=System.currentTimeMillis();
- StringBuffer stringBuffer = new StringBuffer();
- for (int i=0;i<1000000;i++){
- stringBuffer.append(i);
- }
- System.out.println("buffer.append:"+(System.currentTimeMillis()-l) + "ms");
- l=System.currentTimeMillis();
- stringBuffer.toString();
- System.out.println("buffer.toString:"+(System.currentTimeMillis()-l) + "ms");
- l=System.currentTimeMillis();
- StringBuilder stringBuilder = new StringBuilder();
- for (int i=0;i<1000000;i++){
- stringBuilder.append(i);
- }
- System.out.println("builder.append:"+(System.currentTimeMillis()-l) + "ms");
- l=System.currentTimeMillis();
- stringBuilder.toString();
- System.out.println("builder.toString:"+(System.currentTimeMillis()-l) + "ms");
- }
- }
buffer.append:82ms
buffer.toString:9ms
builder.append:36ms
builder.toString:3ms
以上是我本机上的测试结果。
扩展:
示例代码中,对于字符串的拼接直接使用了加号,其实对于部分情况,字符串只是简单拼接,完全可以使用+即可,编译器会根据上下文代码自动优化成StringBuild.append.toString()。大家可以猜测下上述代码也会自动优化吗?
完