Java
IntelliJ IDEA
common-lang-2.6
apache
建议使用commons-lang-2.6.jar中StringUtils.isBlank(String str)来判断字符串是否为空。程序员认为的空字符串一般包含以下几种情况:null,“”,“ ”(n个英文半角空格),“ ”(n个中文全角空格),
使用==来判断。可以看到,与预期一致,返回true示例代码:String whiteSpace = '';String anOtherWhiteSpace = '';System.out.println(whiteSpace == anOtherWhiteSpace);
使用equals来判断。可以看到,与预期一致,返回true示例代码:String whiteSpace = '';String anOtherWhiteSpace = '';System.out.println(whiteSpace.equals(anOtherWhiteSpace));
问题来了,到底应该使用equals,还是==呢?不是说对象比较,要使用equals的嘛。为什么这里使用==也为true呢?这是因为Java中String是不可变对象,为提高性能,在公共方法区,存放了常用的字符。whiteSpace 和anOtherWhiteSpace 引用的是相同的对象,因为内存地址相同,所有在使用==判断时,返回true
同样的空字符串,来看个返回为false的例子:新构建一个内容为空字符串的String对象,这样这个新对象地址和常量池中的就不同了。示例代码:String whiteSpace = '';String whiteSpaceStr = new String(whiteSpace);System.out.println(whiteSpace == whiteSpaceStr);
上面使用==时,空字符串返回true的问题搞清楚了。那怎么来判断字符串为空呢?作为java程序猿,你觉得空字符串长什么样呢?这样的:“”,这样的:null,这样的:new String(''),还是这样的“ ”因此,作为一个公共方法,一定要友好,一定要好用。示例代码:public static boolean isEmpty(String source) { return source == null ||source.isEmpty()||source.trim().isEmpty();}
Apache common-lang 中isEmpty方法中的实现源代码:public static boolean isEmpty(String str) { return str == null || str.length() == 0;}
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; }}