使用if语句检查字符串是否为空时,使用String = null和String.isEmpty()有什么区别吗?
例如:
public String name;
if(name == null)
{
//do something
}
或者public String name;
if(name.isEmpty())
{
//do something
}
如果有任何不同之处(包括性能问题),请告诉我。
空字符串是长度为零的字符串。null值根本没有字符串。
s == null
将返回false
。NullPointerException
异常。这里是显示差异的表格:
+-------+-----------+----------------------+
| s | s == null | s.isEmpty() |
+-------+-----------+----------------------+
| null | true | NullPointerException |
| "" | false | true |
| "foo" | false | false |
+-------+-----------+----------------------+
public static Boolean IsNullOrEmpty(String value){ return (value == null || (value != null && value.isEmpty())); }
现在,在应用程序代码中,我不需要再担心这个结构了:
if(Helper.IsNullOrEmpty(mystring)) { // do something }
- TonyGvalue != null
,因为Java的 if
是懒惰的:如果它到达那个点,它已经不是null了,你可以安全地在值上运行 .isEmpty()
。 - ಠ_ಠ已赋值为“” 的字符串不包含任何值,但是为空(长度=0),未实例化的字符串为null。
变量name
不是一个字符串。它是指向字符串的引用。
因此,空值检查确定name
是否实际上引用了一个String
。如果是,则(仅在这种情况下)可以执行进一步检查以查看其是否为空。即:
String name = null; // no string
String name = ""; // an 'empty' string
这里有两种不同的情况。请注意,如果您没有先检查是否为null,那么您将尝试在空引用上调用方法,这就是当您遇到可怕的NullPointerException
时的情况。
isEmpty()
方法用于检查空字符串 ""
,
如果在 null
实例上调用 isEmpty()
方法,则会抛出 NullPointerException
异常。
查看您的Java版本的源代码。
例如,在openjdk-7中:http://www.docjar.com/html/api/java/lang/String.java.html
119 /** The count is the number of characters in the String. */
120 private final int count;
663 /**
664 * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
665 *
666 * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
667 * <tt>false</tt>
668 *
669 * @since 1.6
670 */
671 public boolean isEmpty() {
672 return count == 0;
673 }
isEmpty 用于检查字符串 ""。 最佳实践是检查:
if (str != null && !str.isEmpty() {
// process string
}
if(name.isEmpty())
{
//do something
}
当name
为null时,您将会收到NullPointerException
异常。
null
检查通常用于检查对象是否存在。
isEmpty
检查通常用于检查现有String
对象的内容是否为空。
public boolean StringIsNull(String pi_sChaine)
{ boolean bTrueOrFalse = true;
if (pi_sChaine == null || pi_sChaine.isEmpty())
{ bTrueOrFalse = true; }
else
{ bTrueOrFalse = false; }
return bTrueOrFalse;
}
null
,而是isEmpty()
。 - Basile Starynkevitch