多语言展示
当前在线:1228今日阅读:23今日分享:25

你知道Java语言确定字符串为空的方法吗?

Java中因为有常量池的存在,在判断字符串为空时,总会有一些不经意的坑。本文分享关于Java中判断字符串为空的相关心得
工具/原料
1

Java

2

IntelliJ IDEA

3

common-lang-2.6

4

apache

方法/步骤
1

建议使用commons-lang-2.6.jar中StringUtils.isBlank(String str)来判断字符串是否为空。程序员认为的空字符串一般包含以下几种情况:null,“”,“  ”(n个英文半角空格),“  ”(n个中文全角空格),

2

使用==来判断。可以看到,与预期一致,返回true示例代码:String whiteSpace = '';String anOtherWhiteSpace = '';System.out.println(whiteSpace == anOtherWhiteSpace);

3

使用equals来判断。可以看到,与预期一致,返回true示例代码:String whiteSpace = '';String anOtherWhiteSpace = '';System.out.println(whiteSpace.equals(anOtherWhiteSpace));

4

问题来了,到底应该使用equals,还是==呢?不是说对象比较,要使用equals的嘛。为什么这里使用==也为true呢?这是因为Java中String是不可变对象,为提高性能,在公共方法区,存放了常用的字符。whiteSpace 和anOtherWhiteSpace 引用的是相同的对象,因为内存地址相同,所有在使用==判断时,返回true

5

同样的空字符串,来看个返回为false的例子:新构建一个内容为空字符串的String对象,这样这个新对象地址和常量池中的就不同了。示例代码:String whiteSpace = '';String whiteSpaceStr = new String(whiteSpace);System.out.println(whiteSpace == whiteSpaceStr);

6

上面使用==时,空字符串返回true的问题搞清楚了。那怎么来判断字符串为空呢?作为java程序猿,你觉得空字符串长什么样呢?这样的:“”,这样的:null,这样的:new String(''),还是这样的“      ”因此,作为一个公共方法,一定要友好,一定要好用。示例代码:public static boolean isEmpty(String source) {        return source == null ||source.isEmpty()||source.trim().isEmpty();}

7

Apache common-lang 中isEmpty方法中的实现源代码:public static boolean isEmpty(String str) {          return str == null || str.length() == 0;}

8

Apache common-lang 中isBlank方法中的实现源代码:public static boolean isBlank(String str) {            int strLen;            if(str != null && (strLen = str.length()) != 0) {                        for(int i = 0; i < strLen; ++i) {                                    if(!Character.isWhitespace(str.charAt(i))) {                                                return false;                                    }                }                return true;        } else {                return true;        }}

推荐信息