StringBuilder append() and null values

后端 未结 8 938
借酒劲吻你
借酒劲吻你 2021-02-06 21:54

I have a list of Strings, and I want to concatenate them with spaces in between. So I\'m using StringBuilder. Now if any of the Strings ar

8条回答
  •  猫巷女王i
    2021-02-06 22:45

    I'm not sure why you'd expect it to come out empty, given that the documentation is pretty clear:

    If str is null, then the four characters "null" are appended.

    Basically you need to either not call append at all if you have a null reference, or switch the value for "".

    You could write a method to do this substitution if you find yourself doing it a lot:

    public static String nullToEmpty(String text) {
        return text == null ? "" : text;
    }
    

    Indeed, I've just looked at the Guava documentation and the Strings class has exactly that method (but with a parameter called string instead of text).

提交回复
热议问题