面试基本点

concat是String方法,String重载了“+”操作符(提醒下:Java不支持其他操作符的重载)。
concat源码:

public String concat(String str) {     
int otherLen = str.length();     
if (otherLen == 0) {         
return this; 
    } 
    char buf[] = new char[count + otherLen]; 
    getChars(0, count, buf, 0); 
    str.getChars(0, otherLen, buf, count); 
    return new String(0, count + otherLen, buf); 
    } 


源码中对String中+操作符的描述如下
引用
The Java language provides special support for the string concatenation operator ( + ), and for conversion of  other objects to strings. String concatenation is implemented  through the StringBuilder(or StringBuffer) class and its append method.

简单的概括下:String本身是不变的对象,但是string的+号操作符是通过StringBuilder或StringBuffer来实现的。两个方法中都有开辟(new)以及销毁堆空间的操作,大量的string操作导致效率很低。所以在大量操作string字符串时,StringBuffer的append方法是最好的选择,StringBuilder是非线程安全的。

String 类型的没有append(StringBuffer的方法)方法,只有concat方法

java是面向对象的语言,所以对象也是java中最基本的元素,而不是接口,方法或者包

猜你喜欢

转载自zengshaotao.iteye.com/blog/2031876