关于String.concat()方法和StringBuffer.append()方法的学习:方法是如何追加字符到源字符串的

问题分析:

首先,看看两段代码的运行结果,两段代码分别是:

第一段代码,关于String.concat()方法的测试:

 1     public static void main(String[] args)
 2     {
 3         //String stringA = "hello";
 4         String stringA = new String("hello");
 5         testConcat test = new testConcat();
 6         
 7         test.change(stringA);
 8         
 9         System.out.println(stringA);
10     }
11     public void change(String stringA)
12     {
13         stringA = stringA.concat("world");
14     }

第二段代码,StringBuffer.append()方法的测试:

 1     public static void main(String[] args)
 2     {
 3         StringBuffer stringBufferA = new StringBuffer("hello");
 4         testAppend test = new testAppend();
 5         
 6         test.change(stringBufferA);
 7         
 8         System.out.println(stringBufferA);
 9     }
10     public void change(StringBuffer stringBufferA)
11     {
12         stringBufferA.append("World");
13     }

在实际的运行这两段代码后,得到的结果是:

第一段代码结果:hello

第二段代码结果:helloWorld

由此,可以看出StringBuffer.append()所改变的是源引用的值,不会依赖于方法返回值,而String.concat()在进行字符串拼接的时候,会产生很多的临时对象来保存,最后在拼接结束后,需要把这个结果临时对象进行返回给接收值进行再指向,需要依赖于方法的返回值,执行的效率也会随着字符数的增加而降低,不是真正的引用源

总结:

在所使用的字符串需要经常变更的情况下,使用StringBuffer效率更高,可以使用StringBuffer进行字符串的变更操作,操作完成后再还给String,操作方法:String -> StringBuffer -> 更改字符串 -> String

待续...

原文地址:https://www.cnblogs.com/Wfei/p/3248922.html