[英]Can we rely on String.isEmpty for checking null condition on a String in Java?
[英]if (String != null && !String.isEmpty()) not working for checking null
我正在檢查 String 是否為 null 但我不知道為什么它總是進入if block
Log.d(TAG,"String ID "+str);
if (str!= null && !str.isEmpty()){
Log.d(TAG,"String ID is not Null ");
} else {
Log.d(TAG,"String ID is Null ");
}
在檢查條件之前,我還生成日志以檢查字符串值,它顯示如下
01-06 07:17:46.128 30321-30376/com.example D/### String Checker ###: Page ID null
01-06 07:17:46.128 30321-30376/com.example D/### String Checker ###: Page ID is not Null
更新:將 String 設置為null
然后像這樣調用其他類
String str = null;
new AsyncTask(searchInterfaceChat,getActivity(),String.valueOf(str)).execute(query);
您正在傳遞字符串值null,因為這是String.valueOf(str);
返回的內容String.valueOf(str);
當str
為null
在查看您的日志時,您的字符串的值似乎是“空”。 你的字符串不為空。 檢查一下。 此觀察僅適用於您的日志
更新代碼后,問題是String.valueOf(str)
,它將 null 轉換為實際上是一個字符串的“null”。 只傳遞str
,而不是String.valueOf(str)
,如new AsyncTask(searchInterfaceChat,getActivity(), str).execute(query);
更新一點解釋
如果您查看代碼String.valueOf()
,如果是 null 對象,它會返回"null"
而不是null
。 所以對你來說,它實際上是"null"
,它被正確地打印在日志上,但會造成混淆。 下面是代碼
/**
* Returns the string representation of the {@code Object} argument.
*
* @param obj an {@code Object}.
* @return if the argument is {@code null}, then a string equal to
* {@code "null"}; otherwise, the value of
* {@code obj.toString()} is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
您可以閱讀Difference between null and empty ("") Java String這不是精確的 QA,但您可以對"null"
和null
有所了解
如果我們想知道,我們可以查看源代碼。 如果字符串長度為零,則 String isEmpty
方法返回 true。
public boolean isEmpty() {
// Android-changed: Get length from count field rather than value array (see above).
// Empty string has {@code count == 0} with or without string compression enabled.
// return value.length == 0;
return count == 0;
}
如果您的對象為空,則方法String.valueOf
將返回“空”。
/**
* @return if the argument is {@code null}, then a string equal to
* {@code "null"}; otherwise, the value of
* {@code obj.toString()} is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
所以當你在其他類中使用它時,它返回的字符串不為空。
為什么不使用 TextUtils.isEmpty() 它會檢查你的兩個條件。
if (!TextUtils.isEmpty("your string")){
Log.d(TAG,"String ID is not Null ");
} else {
Log.d(TAG,"String ID is Null ");
}
還要傳遞字符串,因為在您的情況下,您正在使用字符串類。
嘗試使用 String s=null 和 s="ad" 值在兩種情況下都可以正常工作:
public class Main
{
public static void main(String[] args) {
String str ="ss";
if (str!=null&&!str.isEmpty()){
System.out.println("not Null");
} else {
System.out.println(" Null");
}
}
首先帶上空值,這樣它就不會出錯。
當str
不為null
就可以了
但
如果str
為null
並且你寫str!=null
它將首先嘗試讀取str
但它是null
所以它會給出一個錯誤。
if (null!=str && !str.isEmpty()){
Log.d(TAG,"String ID is not Null ");
} else {
Log.d(TAG,"String ID is Null ");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.