String与StringBuffer
先看下面的例子:
1 public class Test {
2 /**
3 * @param args
4 */
5 public static void main(String[] args) {
6 StringBuffer sb = new StringBuffer("buffer");
7 String s = new String("string");
8 System.out.println(sb);System.out.println(s);
9
10 update(sb);
11 update(s);
12 System.out.println(sb);
13 System.out.println(s);
14 }
15
16 public static void update(Object obj){
17 if(obj instanceof StringBuffer){
18 StringBuffer sb = (StringBuffer)obj;
19 sb.append("successful");
20 }
21 else if(obj instanceof String){
22 String sb = (String)obj;
23 sb += "successful";
24 }
25 }
26 }
2 /**
3 * @param args
4 */
5 public static void main(String[] args) {
6 StringBuffer sb = new StringBuffer("buffer");
7 String s = new String("string");
8 System.out.println(sb);System.out.println(s);
9
10 update(sb);
11 update(s);
12 System.out.println(sb);
13 System.out.println(s);
14 }
15
16 public static void update(Object obj){
17 if(obj instanceof StringBuffer){
18 StringBuffer sb = (StringBuffer)obj;
19 sb.append("successful");
20 }
21 else if(obj instanceof String){
22 String sb = (String)obj;
23 sb += "successful";
24 }
25 }
26 }
输出的结果为:
buffer
string
buffersuccessful
string
查看源码后我们可以了解到如下事实:String进行的操作都需要改变地址;然而StringBuffer的操作首先会判断原来分配的地址空间是否够用,不够用的话就动态的分配地址空间 ,它的引用地址是不会发生改变的。(注意:一般除了基本类型之外的类型都是引用,对象作为参数后会随着所调用方法中的修改而变动,而String比较特殊,他每次都会改变地址)
StringBuffer继承了类AbstractStringBuilder,下面是一个它的构造函数:
1 public AbstractStringBuilder append(String str) {
2 if (str == null) str = "null";
3 int len = str.length();
4 if (len == 0) return this;
5 int newCount = count + len;
6 if (newCount > value.length)
7 expandCapacity(newCount);
8 str.getChars(0, len, value, count);
9 count = newCount;
10 return this;
11 }
2 if (str == null) str = "null";
3 int len = str.length();
4 if (len == 0) return this;
5 int newCount = count + len;
6 if (newCount > value.length)
7 expandCapacity(newCount);
8 str.getChars(0, len, value, count);
9 count = newCount;
10 return this;
11 }