关于java中 String字符拼接符“+“的讨论

程序:


 
 
  1. public class Test {
  2. public static void main(String args[]) {
  3. String s1 = "abc";
  4. String s2 = "abc";
  5. String s3 = "abc" + "def";
  6. String s4 = "abcdef";
  7. String s5 = s2 + "def";
  8. String s6 = new String( "abc");
  9. System. out.println(s1 == s2);
  10. System. out.println(s3 == s4);
  11. System. out.println(s4 == s5);
  12. System. out.println(s4. equals(s5));
  13. System. out.println(s6. equals(s1));
  14. System. out.println();
  15. System. out.print(
  16. "\ns1:"+System.identityHashCode(s1)+
  17. "\ns2:"+System.identityHashCode(s2)+
  18. "\ns3:"+System.identityHashCode(s3)+
  19. "\ns4:"+System.identityHashCode(s4)+
  20. "\ns5:"+System.identityHashCode(s5)+
  21. "\ns6:"+System.identityHashCode(s6));
  22. }
  23. }

 内存模型图:

结果:


 
 
  1. true
  2. true
  3. false
  4. true
  5. true
  6. s1 :557041912
  7. s2 :557041912
  8. s3 :1134712904
  9. s4 :1134712904
  10. s5 :985922955
  11. s6 :1435804085

 
 
  1. 由结果可知
  2. s1和s2指向的地址都是常量池中的 "abc"
  3. s3和s4指向的地址都是常量池中的 "abcdef"
  4. s5和s3并不指向同一个地址,其实s5指向的是对象内存区,也就是s5其实指向了一个对象
  5. s6同理.
  6. 分析:
  7. 字符串用 "+"拼接的时候,如果是两个常量拼接,,不是通过某种方式将两个字符串的地址进行处理,连接两个字符串,而是直接产生一个由两个字符串拼接的新字符串常量;
  8. 字符串用 "+"拼接的时候,如果有变量参与拼接,则产生一个新对象

注意:

String中的“+”运算符本质上是StringBuffer的append()方法(StringBuilder append(String)),所以每次拼接都会新建一个对象,效率极低,而且要注意一个问题,就是方法的运算优先级是最高的,所以极有可能出现意外情况,见下面的例子

原始数据类型会转换成包装类

eg:String s = 1 + "sss";

这里的1本来是int型常量,在进行拼接时,Java进行了类型升级,升级成为了Integer类,并调用了Integer类的toString()方法,将1从数字转换成了字符串,然后再进行拼接

 

所以String在使用“+”进行拼接的时候是非常消耗内存和运行时间的,类似于递归,代码简单,但时间效率和空间效率都非常低

 


 
 
  1. 优先级带来的问题:
  2. 代码:
  3. String s2 = "hello";
  4. String s3 = "hello";
  5. System.out. println( "s2==s3 ?"+s2==s3);
  6. System.out. println( "s2==s3 ? "+(s2==s3));
  7. 结果:
  8. flase(并没有前面的字符串,而且必定 false,无论是什么==什么)
  9. s2==s3 ? true
  10. 结果分析:
  11. "s2==s3 ?"+s2==s3
  12. 等价于:
  13. StringBuilder sb1 = new StringBuilder( "s2==s3 ?");
  14. sb1. append(s2);
  15. String temp = sb1.toString();
  16. boolean bool= temp == s3? true:flase;
  17. String stemp= bool.toString;
  18. System.out. println(stemp);
  19. 注意:字面值连接怒徽降低效率,因为编译器会优化
  20. eg:String s = "asf"+ "sfdf"+ "djkd"+ "dsd"; //这个效率高
  21. boolean tempbool = sb1 ==sb2;
  22. StringBuilder sb3 = new StringBuilder(tempbool.toString());
  23. System.out. println(sb3);

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值