开发者

String[] initialized by null?

Hi i encountered this problem whereby when i initialized my String[], there seems to be a null in the String[] before i do anything. How do i initialized the String[] to b开发者_StackOverflow中文版e completely empty,i.e. without the null at the start? The output for the following code is:

nullABC

nullABC

nullABC

nullABC

nullABC

public static void main(String[] args){
    String[] inputArr = new String[5];
    for (int i = 0; i< inputArr.length; i++){
        inputArr[i] += "ABC";
    }
    for (int i = 0; i< inputArr.length; i++){
        System.out.println(inputArr[i]);
    }
}

}


A null reference is about as empty as a string array element can be. Note that there's a big difference between a reference to the empty string and a null reference though. Just change your code to use simple assignment instead of +=.

for (int i = 0; i< inputArr.length; i++){
    inputArr[i] = "ABC";
}

If you need to do conditional concatenation elsewhere, use something like this:

for (int i = 0; i< inputArr.length; i++) {
    String current = inputArr[i];
    String suffix = "ABC";
    String replacement = current == null ? suffix : current + suffix;
    inputArr[i] = replacement;
}

Alternatively, you could use something like this:

public static String emptyForNull(String x) {
    return x == null ? "" : x;
}

and then have:

for (int i = 0; i< inputArr.length; i++){
    inputArr[i] = emptyForNull(inputArr[i]) + "ABC";
}

Or (yes, lots of available options):

public static String nullAwareConcat(String x, String y) {
    return x == null && y == null ? ""
        : x == null ? y
        : y == null ? x
        : x + y;
}

...

for (int i = 0; i< inputArr.length; i++){
    inputArr[i] = nullAwareConcat(inputArr[i], "ABC");
}


Change:

inputArr[i] += "ABC";

To:

inputArr[i] = "ABC";

Or (like Jon Skeet mentioned) you can use a conditional statement to either initialize or concat the strings:

inputArr[i] = inputArr[i] == null ? "ABC" : inputArr[i] + "ABC";


The null in the array isn't the string "null", but the value null. If you want to initialize it with empty strings, do:

for (int i = 0; i < inputArr.length; i++) {
    inputArr[i] = "";
}


Others gave pretty good answers concerning "emptiness" of an array and assignment operator. Just let me add another way to initialize an array:

String[] inputArr = new String[5];
java.util.Arrays.fill(inputArr, "ABC");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜