A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© wangyafeng1990 中级黑马   /  2013-10-19 22:28  /  2935 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

求解答,越详细越好

4 个回复

倒序浏览
本帖最后由 周学彬 于 2013-10-19 23:44 编辑

concat()方法是String类的一个方法,要由一个String类对象调用,而且需要传递一个String类对象作为参数。结果返回的是两个String类对象拼接成的对象。
+是String类重载的一个操作符。在处理String对象时,需要创建一个StringBuffer对象,然后用这个对象的append()方法进行拼接,最后将拼接成的对象调用toString()方法,返回一个字符串对象。
通过concat的源码也可以看出,在使用concat()方法时,也要预先分配一段内存空间,该内存空间用于存放一个字符数组,然后将两个String类对象都复制到这个数组中,最后将该数组转换成String对象并返回。
concat源码如下:
  1. public String concat(String str) {
  2.         int otherLen = str.length();
  3.         if (otherLen == 0) {
  4.             return this;
  5.         }
  6.         char buf[] = new char[count + otherLen];
  7.         getChars(0, count, buf, 0);
  8.         str.getChars(0, otherLen, buf, count);
  9.         return new String(0, count + otherLen, buf);
  10.     }
复制代码
所以,两种方法在内存使用上,都是要先创建一段空间,然后销毁。区别就是使用形式上,一个是方法,另一个是重载了一个运算符

评分

参与人数 1技术分 +1 收起 理由
周志龙 + 1

查看全部评分

回复 使用道具 举报
要看看他们之间的区别,我们可以从源码分析两者的区别,
concat是String方法,String重载了“+”操作符(提醒下:Java不支持其他操作符的重载)。
concat源码:
  1.       public String concat(String str) {      
  2.     int otherLen = str.length();      
  3.     if (otherLen == 0) {         
  4.     return this;  
  5.         }  
  6.         char buf[] = new char[count + otherLen];  
  7.         getChars(0, count, buf, 0);  
  8.         str.getChars(0, otherLen, buf, count);  
  9.         return new String(0, count + otherLen, buf);  
  10.         }  
复制代码
源码中对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(可以通过反汇编class文件,看到使用的StringBuilder来实现的。)
=========================
以上两个方法中都有开辟(new)以及销毁堆空间的操作,打大量的string操作导致效率很低。
所以在大量操作string字符串时,StringBuilder的append方法是最好的选择

评分

参与人数 1技术分 +1 收起 理由
周志龙 + 1 很给力!

查看全部评分

回复 使用道具 举报
To 金牌黑马 2013-10-20 19:10:38
板凳
楼主你好,如果问题已解决请将帖子状态修改为提问结束,如果未解决请继续提问,谢谢合作
如果不会修改请看解释帖:http://bbs.itheima.com/thread-89313-1-1.html
回复 使用道具 举报
它们都可以将两个字符串连接到一块,这一点两者功能相同
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马