字符串连接concat()和+运算符有效使用(String concatenation concat() and + operator usage effectively)

编程入门 行业动态 更新时间:2024-10-17 05:36:59
字符串连接concat()和+运算符有效使用(String concatenation concat() and + operator usage effectively)

我知道字符串连接:concat()vs“+”运算符

但我有效地使用了concat()和+运算符

concat()比+运算符更有效,但在下面的几个例子中我们仍然使用+运算符

情况1

System.out.println("Hi! Welcome: "+nameString);

案例2:

将巨大的长度线分成多行(eclipse格式化)

System.out.println("Hi! Welcome: "+nameString1 +nameString2 +nameString3);

为什么我们仍然使用+运算符而不是concat() ?

I am aware of String concatenation: concat() vs "+" operator

But i have question on usage of both concat() and + operator effectively

concat() is more efficient than + operator but still we are using + operator in few cases below

Case 1

System.out.println("Hi! Welcome: "+nameString);

Case 2:

splitting huge length line in to multiple lines(eclipse formatting)

System.out.println("Hi! Welcome: "+nameString1 +nameString2 +nameString3);

why still we are using + operator instead of concat()?

最满意答案

有区别。

如果aStr为null,则aStr.concat(bStr) >> NPE s 但是如果aStr += bStr会将aStr += bStr的原始值视为null 。

此外, concat()方法只接受String而不是+运算符,它将参数转换为String (使用Object.toString() )。

所以concat()方法在它接受的内容中更严格。

此外,如果你有很多串连接与concat()或+ ,我强烈建议使用可变的StringBuilder对象,这将提高代码的速度。

There's are difference.

If aStr is null, then aStr.concat(bStr) >> NPEs but if aStr += bStr will treat the original value of aStr as if it were null.

Also, the concat() method accepts just String instead the + operator which converts the argument to String (with Object.toString()).

So the concat() method is more strict in what it accepts.

Also, if you have lot of String concatenations with concat() or +, I highly recommend to work with mutable StringBuilder object that will increase speed of your code.

更多推荐

本文发布于:2023-08-07 12:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464494.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   运算符   concat   String   effectively

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!