我知道字符串连接: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.
更多推荐
发布评论