TextUtils.isEmpty(string)和string.isEmpty之间的区别是什么
两者执行相同的操作。
使用TextUtils.isEmpty(string)是否有优势
发布于 2016-04-04 01:21:04
是的,TextUtils.isEmpty(string)是首选。
对于string.isEmpty(),null字符串值将引发NullPointerException
TextUtils将始终返回布尔值。
在代码中,前者只是简单的calls the equivalent of the other,加上一个空检查。
return string == null || string.length() == 0;发布于 2016-04-04 01:25:57
在类TextUtils中
public static boolean isEmpty(@Nullable CharSequence str) {
if (str == null || str.length() == 0) {
return true;
} else {
return false;
}
}检查字符串长度是否为零以及字符串是否为null,以避免引发NullPointerException
在类String中
public boolean isEmpty() {
return count == 0;
}检查字符串长度是否仅为零,如果尝试使用该字符串且字符串为空,则可能会导致NullPointerException。
发布于 2016-04-04 01:29:51
看一下文档
对于他们指定的String#isEmpty:
布尔值
当且仅当isEmpty()为0时,length()返回true。
对于TextUtils.isEmpty,文档解释如下:
公共静态布尔字符串(CharSequence isEmpty )
如果字符串为空或长度为0,则返回true。
所以主要的区别是使用TextUtils.isEmpty,你不关心或者不需要检查字符串是否为空引用,
在另一种情况下,是的。
https://stackoverflow.com/questions/36388581
复制相似问题