在java中我们经常可以看到StringBuffer和String的用法,但是我自己在使用过程中,经常会将两者弄混淆,今天我们就来了解一下两者的区别:
我们首先来看一下我们的官方API中的简单介绍:
A string buffer is like a String
, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
官方文档中介绍:StringBuffer 和String在很多时候都是相似的。但是StringBuffer有个最明显的特征:synchronized
The principal operations on a StringBuffer
are the append
and insert
methods, which are overloaded so as to accept data of any type.
StringBuffer中最主要的方法为Append 和Insert方法。
StringBuffer在追加字符串,删除字符串,插入字符方面的速度优于String。
最主要的区别:
对于StringBuffer对象的每次修改都会改变对象自身
String first = "bei";
String second = "jing";
StringBuffer sb = new StringBuffer(first);
StringBuffer sb2 = sb;
sb2.append(second);
System.out.println(sb2); //beijing
System.out.println(sb.equals(sb2)); //true
1:StringBuffer对象的初始化
StringBuffer sBuffer = new StringBuffer("shanghai");
利用给定的方法来初始化buffer对象
StringBuffer 和String之间不能直接转化,下面的代码会提示错误。
StringBuffer sb3 = "nanjing";
当然,两者可以互相转化的,比如:
StringBuffer sBuffer = new StringBuffer("shanghai"); //String转化为buffer对象
String add = sBuffer.toString(); //buffer对象转化成String类型
2:追加字符串
sb.append(String str)
在后面追加字符串
String second = "jing";
StringBuffer sb = new StringBuffer("bei");
sb.append(second); //beijing
3:删除字符
StringBuffer sb = new StringBuffer("beijing");
sb.delete(0, 1); //eijing (左闭右开)
删除特定下标的字符:
StringBuffer sb = new StringBuffer("beijing");
sb.deleteCharAt(1) //bijing
3:插入字符
StringBuffer.insert(int offset, String str)
offset : 表示插入字符的位置
str:插入的字符串
StringBuffer sb = new StringBuffer("beijing");
sb.insert(0, "go to "); //go to beijing
4:倒转字符串
StringBuffer sb = new StringBuffer("beijing");
System.out.println(sb.reverse()); //gnijieb
5:修改某一个特定位置的字符
StringBuffer sb = new StringBuffer("beijing");
sb.setCharAt(0, 'B'); //Beijing
回到最开始的标题部分那么StringBuffer和StringBuilder有什么区别呢?
两者的功能基本一样,都是适合与可操作性的,唯一的区别在StringBuffer is synchronized(同步)。
StringBuilder is not
synchronized。在速度方面StringBuilder速度远远快于StringBuilder.
因此,一般情况下,我们都用StringBuilder代替StringBuffer.
----------------------------------------------------官方API介绍----------------------------------------------------------------------、
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.
-------------------------------------------------------完结-------------------------------------------------------