烟_火
人间烟火何不尝

首先先看一个字符串拼接的例子:

public static void main(String[] args) {
        String testStr = null + "test";
        System.out.println(testStr);
        
    }

 

这个结果可能又可能与大家想的不同:

 

 其实出现这种情况的原因就是String.valueOf方法将null值会转变为"null"进行拼接,比较坑(testStr = testStr+"test"; 等价于 testStr = String.valueOf(testStr)+"test";)

public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

  

其实这种情况的解决办法有很多,下面我列举2个:

1、if判断

public static void main(String[] args) {
        String testStr = null;
        testStr = testStr == null? "test" : testStr + "test";;
        System.out.println(testStr);
    }

  

2、java 8 的Option.ofNullable()方法

public static void main(String[] args) {
        String testStr = null;
        testStr = Optional.ofNullable(testStr).orElse("") + "test";
        System.out.println(testStr);
    }

  

其他方法也有,基本都是先进行判空然后再进行拼接,不过大佬们若有好的方法可以留下评论,供类似我这种小菜学习!!

 

 

 

 

  

posted on 2021-09-02 11:16  段流儿  阅读(1820)  评论(0编辑  收藏  举报