简体   繁体   English

Android TextUtils isEmpty vs String.isEmpty

[英]Android TextUtils isEmpty vs String.isEmpty

What is difference between TextUtils.isEmpty(string) and string.isEmpty ? TextUtils.isEmpty(string)string.isEmpty什么string.isEmpty

Both do the same operation. 两者都做同样的操作。

Is it advantageous to use TextUtils.isEmpty(string) ? 使用TextUtils.isEmpty(string)是否有利?

Yes, TextUtils.isEmpty(string) is preferred. 是的,首选TextUtils.isEmpty(string)


For string.isEmpty() , a null string value will throw a NullPointerException 对于string.isEmpty() ,空字符串值将抛出NullPointerException

TextUtils will always return a boolean value. TextUtils将始终返回一个布尔值。

In code, the former simply calls the equivalent of the other , plus a null check. 在代码中,前者只调用另一个的等价物 ,加上空检查。

return string == null || string.length() == 0;

In class TextUtils 在类TextUtils

public static boolean isEmpty(@Nullable CharSequence str) {
    if (str == null || str.length() == 0) {
        return true;
    } else {
        return false;
    }
}

checks if string length is zero and if string is null to avoid throwing NullPointerException 检查字符串长度是否为零,以及string是否为null以避免抛出NullPointerException

in class String 在类String

public boolean isEmpty() {
    return count == 0;
}

checks if string length is zero only, this may result in NullPointerException if you try to use that string and it is null. 检查字符串长度是否仅为零,如果您尝试使用该字符串并且它为null,则可能导致NullPointerException

Take a look at the doc 看看文档

for the String#isEmpty they specify: 对于String#isEmpty,它们指定:

boolean 布尔
isEmpty() Returns true if, and only if, length() is 0. isEmpty()当且仅当length()为0时返回true。

and for the TextUtils.isEmpty the documentation explains: 对于TextUtils.isEmpty文档说明:

public static boolean isEmpty (CharSequence str) public static boolean isEmpty(CharSequence str)

Returns true if the string is null or 0-length. 如果字符串为null或0-length,则返回true。

so the main difference is that using the TextUtils.isEmpty, you dont care or dont need to check if the string is null referenced or not, 所以主要区别在于使用TextUtils.isEmpty,你不关心或者不需要检查字符串是否为null引用,

in the other case yes. 在另一种情况下是的。

TextUtils.isEmpty() is better in Android SDK because of inner null check, so you don't need to check string for null before checking its emptiness yourself. 由于内部空检查, TextUtils.isEmpty()在Android SDK中更好,所以在自己检查空虚之前,不需要检查字符串是否为null。

But with Kotlin, you can use String?.isEmpty() and String?.isNotEmpty() instead of TextUtils.isEmpty() and !TextUtils.isEmpty() , it will be more reader friendly 但是使用Kotlin,你可以使用String?.isEmpty()String?.isNotEmpty()而不是TextUtils.isEmpty()!TextUtils.isEmpty() ,它会更友好的读者

So I think it is preferred to use String?.isEmpty() in Kotlin and TextUtils.isEmpty() in Android Java SDK 所以我认为首选在Kotlin中使用String?.isEmpty()和在Android Java SDK中使用TextUtils.isEmpty()

String?.isNullOrEmpty

可能就是你要找的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM