TextUtils.isEmpty(string)
和之间有什么区别string.isEmpty
?
两者都做同样的操作.
使用有利TextUtils.isEmpty(string)
吗?
cri*_*007 70
是的,TextUtils.isEmpty(string)
是首选.
对于string.isEmpty()
,null字符串值将抛出一个NullPointerException
TextUtils
将始终返回一个布尔值.
在代码中,前者只调用另一个的等价物,加上空检查.
return string == null || string.length() == 0;
Run Code Online (Sandbox Code Playgroud)
在班上 TextUtils
public static boolean isEmpty(@Nullable CharSequence str) {
if (str == null || str.length() == 0) {
return true;
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
检查字符串长度是否为零,如果string为null则避免抛出 NullPointerException
在班上 String
public boolean isEmpty() {
return count == 0;
}
Run Code Online (Sandbox Code Playgroud)
检查字符串长度是否仅为零,NullPointerException
如果您尝试使用该字符串并且它为null ,则可能会导致这种情况.
看看文档
对于String#isEmpty,它们指定:
boolean
isEmpty()当且仅当length()为0时,返回true.
对于TextUtils.isEmpty 文档说明:
public static boolean isEmpty(CharSequence str)
如果字符串为null或0-length,则返回true.
所以主要区别在于使用TextUtils.isEmpty,你不关心或者不需要检查字符串是否为null引用,
在另一种情况下是的.
TextUtils.isEmpty()
最好在Android SDK中使用,因为它具有内部null检查功能,因此您无需先检查string是否为null即可自己检查其是否为空。
但是使用Kotlin,您可以使用String?.isEmpty()
和String?.isNotEmpty()
代替TextUtils.isEmpty()
和!TextUtils.isEmpty()
,它将对读者更友好
所以我认为最好String?.isEmpty()
在Kotlin和TextUtils.isEmpty()
Android Java SDK中使用