Java中因为有常量池的存在,在判断字符串为空时,总会有一些不经意的坑。
本文分享关于Java中判断字符串为空的相关心得
前期准备工作(包括相关工具或所使用的原料等)JavaIntelliJ IDEAcommon-lang-2.6apache 详细的操作方法或具体步骤
建议使用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;
}
}

- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
