简体   繁体   English

字符串串联concat()和+运算符的有效使用

[英]String concatenation concat() and + operator usage effectively

I am aware of String concatenation: concat() vs "+" operator 我知道字符串串联:concat()vs“ +”运算符

But i have question on usage of both concat() and + operator effectively 但是我对有效使用concat()和+运算符有疑问

concat() is more efficient than + operator but still we are using + operator in few cases below concat()+运算符更有效,但在以下几种情况下我们仍使用+运算符

Case 1 情况1

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

Case 2: 情况2:

splitting huge length line in to multiple lines(eclipse formatting) 将长行分割成多行(Eclipse格式)

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

why still we are using + operator instead of concat() ? 为什么我们仍然使用+运算符而不是concat()

There's are difference. 有区别。

If aStr is null, then aStr.concat(bStr) >> NPE s 如果aStr为null,则aStr.concat(bStr) >> NPE s
but if aStr += bStr will treat the original value of aStr as if it were null . 但是,如果aStr += bStr会治疗的初始值aStr就好像它是null

Also, the concat() method accepts just String instead the + operator which converts the argument to String (with Object.toString() ). 另外, concat()方法仅接受String而不是+运算符,该运算符将参数转换为String (带有Object.toString() )。

So the concat() method is more strict in what it accepts. 因此, concat()方法接受的条件更加严格。

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. 另外,如果您使用concat()+进行大量String串联操作,强烈建议使用可变的StringBuilder对象,这将提高代码速度。

I agree with you about concat() efficiency, but look into few issue with it, 对于concat()的效率,我同意您的看法,但对此并没有太多疑问,

For concat(String str) 对于concat(String str)

concat() is more strict about its argument means it only accept String not any other primitive or wrapper data type (Signature concat(String str)). concat()对其参数更为严格,这意味着它仅接受String而不接受任何其他原始或包装数据类型(签名concat(String str))。 String a = null, String b = "ABC"; 字符串a = null,字符串b =“ ABC”; b.concat(a) Throw null pointer exception. b.concat(a)抛出空指针异常。

for + accept all data type(wrapper or primitive) where as if you work with a+=b there wont any NPE operator will silently convert the argument to a String (using the toString() method for objects) for +接受所有数据类型(包装器或原始数据),就像使用a + = b一样,任何NPE运算符都不会将参数静默转换为字符串(使用toString()对象的方法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM