append()方法的坑

我们经常会用到StringBuilder或StringBuffer类的append()方法,然而这里有个坑。

public static void main(String[] args) {

        String ab = null;
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("测试");

        if(null== ab) {
            stringBuffer.append(ab);
        }

        System.out.println(ab);
        System.out.println(stringBuffer.toString());

    }
输出:
null
测试null

多了一个null字符串。

下面是撸源码时间←_←

java.lang.StringBuffer#append(java.lang.String)

    public synchronized StringBuffer append(String str) {
        super.append(str); //关键从这里进入
        return this;
    }

java.lang.AbstractStringBuilder#append(java.lang.String)

    /**
     * Appends the specified string to this character sequence.
     * <p>
     * The characters of the {@code String} argument are appended, in
     * order, increasing the length of this sequence by the length of the
     * argument.   这里: If {@code str} is {@code null}, then the four
     * characters {@code "null"} are appended.
     * 如果入参str是null,那么就会把“null”字符串给append进去。
     * <p>
     * Let <i>n</i> be the length of this character sequence just prior to
     * execution of the {@code append} method. Then the character at
     * index <i>k</i> in the new character sequence is equal to the character
     * at index <i>k</i> in the old character sequence, if <i>k</i> is less
     * than <i>n</i>; otherwise, it is equal to the character at index
     * <i>k-n</i> in the argument {@code str}.
     *
     * @param   str   a string.
     * @return  a reference to this object.
     */
    public AbstractStringBuilder append(String str) {
        if (str == null) str = "null"; //就是这一步
        int len = str.length();
        ensureCapacityInternal(count + len);
        str.getChars(0, len, value, count);
        count += len;
        return this;
    }

上面的源码注释说的明明白白,jdk给多此一举的转换了[捂脸]!!!

所以如果你在组装返回给前端的数据时,使用到了append()方法,那么当你像下面的栗子一样使用append()方法时,请注意判空,负责会发生神马。。。。。。我神马都不知道,我神马都没说[捂脸]!!!:

append(coupon.getName());

改为:
String couponName = coupon.getName();
if(StringUtils.isNotBlank(couponName )){
    append(couponName );
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home...
    光剑书架上的书阅读 9,405评论 2 8
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,051评论 18 399
  • 集合框架: 1)特点:存储对象;长度可变;存储对象的类型可不同2)Collection(1)List:有序的;元素...
    Demo_Yang阅读 5,071评论 0 4
  • 为什么要做这样一个挑战? 就是想把自己那点活儿干明白。 起始时间:2017年7月10日-2017年12月31日,共...
    幺幺是我阅读 3,671评论 19 1
  • 文/云笙 1 我骑着车子经过被树林遮盖的小道,风穿过我的耳朵,周围都是和我一样穿着校服的人群。 他们欢呼着,热烈地...
    云笙阅读 2,895评论 1 5