2016-04-03 6 views
18

TextUtils.isEmpty(string)string.isEmptyの違いは何ですか?Android TextUtils isEmpty vs String.isEmpty

どちらも同じ操作です。

TextUtils.isEmpty(string)を使用すると効果的ですか?

+1

あなたは、ちょうど数秒であなた自身の違いを理解するために、常に両方の方法の実装を見ることができます。 –

+1

TextUtilsソースコード:http://grepcode.com/file/repository.grepcode.com /java/ext/com.google.android/android/5.1.1_r1/android/text/TextUtils.java#TextUtils.isEmpty%28java.lang.CharSequence%29 –

答えて

31

はい、TextUtils.isEmpty(string)が好ましい


string.isEmpty()については、ヌル文字列値がNullPointerException

TextUtilsは常にブール値を返しますスローされます。

コードでは、前者は単純にcalls the equivalent of the otherにヌルチェックを加えたものです。

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

@RuchirBaroniaは 'TextUtils。'String'オブジェクトが' null'かどうかをチェックし、 'String'を使用しようとすると' NullPointerException'を取得しませんでした –

+0

@ahmedghanayemいいえ、私はクリケットがString# String.isEmptyの代わりにisEmptyを使用しましたが、そのリンクが私のためにクリアしました。 –

+0

私は、単に混乱を避けるために、クラスの代わりに変数を使うことができることに気付きました。 –

3
クラスにおいて

TextUtils

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

チェックする文字列の長さはゼロであり、文字列がnullの場合、文字列の長さがあればクラスにString

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

チェックをNullPointerException

を投げ回避する場合ゼロのみである場合、これは0123その文字列を使用しようとすると、、それはnullです。

4

彼らは指定String#isEmptyのためのdoc

を見てみましょう:、および場合のみ、長さ()は0

ある場合にtrueを返します

ブール
のisEmpty()を

およびTextUtils.isEmptyの場合、ドキュメントには次のような説明があります。

public static boolean isEmpty(CharSequence str)

文字列がヌルまたは長さ0の場合はtrueを返します。

ので、主な違いは、はい、他の場合には、TextUtils.isEmptyを使用して、あなたが気にしないか、文字列がnullで参照されているかどうかをチェックする必要がいけないということ

です。

+0

'TextUtils.isEmpty'のドット表記は静的メソッドなので意味があると思います –

関連する問題