如果条件错误,有人可以在下面建议我吗?

时间:2016-09-14 04:26:05

标签: android string null equals

编码中的任何异常都可能发生,因为检查字符串是否为null?请帮忙。

String code ;

if (!code.equals(null)) {

}
else
{

}

6 个答案:

答案 0 :(得分:1)

以下是检查String值是否为空的方法

if(code != null){

}else{

}

您不能!code.equals(null),因为equals用于比较相同的对象类型。 null不是任何对象类型,代码String。如果您将null视为String,则可以使用!code.equals("null")

答案 1 :(得分:0)

可以像这样检查字符串:

if(code.equals("null") || code.equals("")) {
     // code to do when string is null.
 }
else {
     // code to do when string is not null.
 }

答案 2 :(得分:0)

equals()用于检查两个String的相似度,==!=用于检查条件。在你的情况下,你正在检查字符串的相似性。

if (!code.equals(null)) {
//code checks that String code is equal to null or not
}
else
{ 
} 

另一个

if (code != null) {
//code checks if code is not equals to null (condition checking)
}
else
{
}

答案 3 :(得分:0)

有很多方法可以检查Java中的String是否为空,但是正确的方法是什么?在稳健性,性能和可读性方面。如果健壮性是您的首要任务,那么使用equals()方法或Apache commons StringUtils是执行此检查的正确方法。如果您不想使用第三方库并且乐于自己进行空检查,那么检查String的长度是最快的方法,并且使用String中的isEmpty()方法是最可读的方式。顺便说一句,不要在空字符串和空字符串之间混淆,如果你的应用程序将它们视为相同,那么你可以认为它们相同,否则它们是不同的,因为null可能不被归类为空。以下是使用JDK库本身检查String是否为空的三个示例。

Read more Here

答案 4 :(得分:0)

您无法使用.equals(null)进行空检查,因为Object#equals的API说明指出:

  

对于任何非空引用值x,x.equals(null)应返回false。

这不仅是一个无用的检查(因为它总是返回false),如果NullPointerException实际上是code,它也会抛出null,因为{ {1}}值未定义null方法。

equals

进行空检查的唯一实用方法是使用:

Object x = null;
boolean isNull = x.equals(null); // NullPointerException on .equals

答案 5 :(得分:0)

如果您想检查字符串是否为空,例如null"",请使用

if(TextUtils.isEmpty(code)){

}else{

}

equals检查字符串中是否存在该值。