简体   繁体   English

Java字符串串联-有更好的方法吗?

[英]Java string concatenation - is there a better way?

Just a quick form question. 只是一个简单的表格问题。 In the following code, is there a better way to concatinate the strings (ie can I just set tmpError equal to the new string rather than adding it?) 在下面的代码中,有没有更好的方法来隐藏字符串(即,我是否可以将tmpError设置为等于新字符串而不是将其添加?)

public void validate () throws Exception {
    String tmpError = "";
    if(paramA == null) tmpError = tmpError + "paramA was not set";

    if(paramB == null) tmpError = tmpError + "paramB was not set";

    if(paramC == null) tmpError = tmpError + "paramC was not set";


    if(!tmpError.equalsIgnoreCase("")){
        tmpError = "error occured" + tmpError;
        throw new Exception(tmpError);
    }
}

Thanks in advance 提前致谢

It can be easily improved in efficiency by using StringBuilder . 使用StringBuilder可以很容易地提高效率。

Due to the immutable nature of String , every time you use the addition ( + ) operator for String concatenation, a new String object is allocated (it also does when using String.concat() ). 由于String ,每当您对字符串串联使用加法( + )运算符时,都会分配一个新的String对象(使用String.concat()时也会如此)。

StringBuilder keeps an internal character array, so that concatenation operations work on that array and only one String object is allocated when you call its toString() method. StringBuilder保留一个内部字符数组,以便在该数组上进行串联操作,并且在调用其toString()方法时仅分配一个String对象。 Use its append() method to append text to the end of the String, and use insert() with offset 0 to prepend text. 使用其append()方法将文本附加到String的末尾,并使用偏移量为0的insert()附加文本。

However, you should also take into account readability. 但是,您还应该考虑可读性。 Dasblinkenlight made a good point in his answer . Dasblinkenlight在他的回答中指出了一个很好的观点。 And as Anthony has already pointed out, you could also use the += compound assignment operator to enhance readability. 正如Anthony所指出的,您还可以使用+=复合赋值运算符来增强可读性。

public void validate () throws Exception {
    StringBuilder tmpError = new StringBuilder();
    if(paramA == null) tmpError.append("paramA was not set");

    if(paramB == null) tmpError.append("paramB was not set");

    if(paramC == null) tmpError.append("paramC was not set");


    if(tmpError.length() > 0){
        tmpError.insert(0,"error occured");
        throw new Exception(tmpError.getString());
    }
}

I would always advise the use of the StringBuilder 我总是建议使用StringBuilder

something like this: 像这样的东西:

public void validate() throws Exception {
    StringBuilder error = new StringBuilder();
    if(paramA == null)
        error.append("paramA was not set");

    if(paramB == null)
        error.append("paramB was not set");

    if(paramC == null)
        error.append("paramC was not set");


    if(error.length() > 0) {

        throw new Exception("error occured " + error.toString());
    }
}

您可以使用+= (添加/串联和赋值)运算符:

if(paramA == null) tmpError += "paramA was not set";

This is not efficient, because with all three params missing you will create four string objects. 这效率不高,因为在缺少所有三个参数的情况下,您将创建四个字符串对象。 You would be better off appending to a single StringBuilder object. 您最好追加一个StringBuilder对象。

However, this is error reporting code which gets executed only when your code detects a programming error. 但是,这是错误报告代码,仅在代码检测到编程错误时才执行。 Efficiency does not matter much in situations like that, because they are not supposed to happen in the first place. 在这种情况下,效率并不重要,因为首先不应该发生这种情况。 Use whatever you believe to be easier to understand. 使用您认为更容易理解的任何内容。

Do it like this: 像这样做:

public void validate () throws Exception {
    String tmpError = "";
    if(paramA == null) tmpError += "paramA was not set";

    if(paramB == null) tmpError += "paramB was not set";

    if(paramC == null) tmpError += "paramC was not set";


    if(!tmpError.equalsIgnoreCase("")){
        tmpError = "error occured" + tmpError;
        throw new Exception(tmpError);
    }
}

Or alternatively, you can use a StringBuilder as pointed out by Xavi, but to me that would only make sense, if you were appending text inside some sort of loop. 或者,您可以使用Xavi指出的StringBuilder ,但对我来说,只有在将文本附加到某种循环中时才有意义。

Fastest way to concatenation two strings is concat function of String class. 连接两个字符串的最快方法是String类的concat函数。

public void validate () throws Exception {
    String tmpError = "";

    if(paramA == null) tmpError = tmpError.concat("paramA was not set");
    if(paramB == null) tmpError = tmpError.concat("paramB was not set");
    if(paramC == null) tmpError = tmpError.concat("paramC was not set");
    if(!tmpError.equalsIgnoreCase("")){
        tmpError = "error occured".concat(tmpError);
        throw new Exception(tmpError);
    }
}

Rather than any of the above, you might want to use Guava Preconditions . 除了上面的任何一个,您可能想要使用Guava Preconditions Then you could write code like this: 然后,您可以编写如下代码:

import static com.google.common.base.Preconditions.*;
...
public void doSomething(String strA, String strB) {
  checkNotNull(strA, "strA is missing");
  checkArgument(strB.length() >= 6, "strB is too short");
  ...
}

If the check fails, then an Exception is thrown. 如果检查失败,那么Exception被抛出。 It might not be quite as succinct as your original solution, but your intention is semantically obvious. 它可能不像您最初的解决方案那么简洁,但是您的意图在语义上是显而易见的。

I would do something as below public void validate () throws Exception { 我会做以下公共无效validate()抛出异常{

public void validate () throws Exception {
    String tmpError = "";
    if(paramA == null) tmpError += "paramA was not set";
    if(paramB == null) tmpError += "paramB was not set";
    if(paramC == null) tmpError += "paramC was not set";

    if(!(tmpError.trim()).equalsIgnoreCase("")){
        tmpError = "error occured" + tmpError;
        throw new Exception(tmpError);
    }
}

See I've used += and trimmed the tmpError variable before checking its empty. 请参阅我使用+=并在检查tmpError变量为空之前对其进行了修剪。

I don't think here you don't need to worry much about StringBuilder as not much memory is being handled in this scenario. 我认为这里您不需要为StringBuilder担心,因为在这种情况下不会处理太多内存。

If you are insisting on StringBuilder then you may do something as below 如果您坚持使用StringBuilder,则可以执行以下操作

public void validate () throws Exception {
    StringBuilder sb = new StringBuilder();
    if(paramA == null) sb.append("paramA was not set");
    if(paramB == null) sb.append("paramB was not set");
    if(paramC == null) sb.append("paramC was not set");

    if(!(sb.toString().trim()).equalsIgnoreCase("")){
        sb.Insert(0,"error occured");
        throw new Exception(sp.toString());
    }
}

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

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