StringBuilder的追加null作为"零" [英] StringBuilder appends null as "null"

查看:333
本文介绍了StringBuilder的追加null作为"零"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么?

    StringBuilder sb = new StringBuilder();

    sb.append("Hello");
    sb.append((String)null);
    sb.append(" World!");
    Log.d("Test", sb.toString());

生成

18 06-25:24:24.354:D /测试(20740): Hellonull世界

06-25 18:24:24.354: D/Test(20740): Hellonull World!

我希望追加字符串的不追加在所有!! 的结果
顺便说一句,演员到字符串是必要的,因为 StringBuilder.append()有很多重载版本。

I expect that appending a null String will not append at all!!
BTW, the cast to String is necessary because StringBuilder.append() has a lot of overloaded versions.

我简化我的code键使点在这里,在我的code进行了返回一个字符串的方法

I simplified my code to make a point here, in my code a got a method returning a string

public String getString() { ... }
...
sb.append(getString());
...

的getString()有时会返回;现在我就来测试一下,如果我想使用的StringBuilder !!!!

getString() sometimes returns null; now I have to test it if I want to use a StringBuilder!!!!

此外,让我们在这里澄清我的问题:我如何获得 StringBuilder.append()来接受,在一个优雅的方式,一个空字符串,而不是将其转换为文本字符串空。结果
由优雅我的意思是我不想要得到的字符串,测试,如果是,然后才追加它。我在找一个优雅oneliner。

Furthermore, let's clarify my question here: how can I get StringBuilder.append() to accept, in an elegant way, a null string, and not convert it to the literal string "null".
By elegant I mean I don't want to get the string, test if it is null and only then append it. I am looking for an elegant oneliner.

推荐答案

这只是事情是这样的。 被追加为。同样,当您打印的System.out.println(空)打印

That's just the way it is. null is appended as "null". Similarly, when you print null with System.out.println(null) you print "null".

要避免的方法是返回字符串的方法的getString()检查

The way to avoid that is that method that returns string getString() checks for null:

public String getString() {
    ...
    if (result == null) {
        return "";
    }
}

这篇关于StringBuilder的追加null作为"零"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆