Java 将对象与 null 进行比较!
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/994430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
compare an object to null!
提问by fenec
I am trying to verify whether an object is null or not and i am using this syntax:
我正在尝试验证对象是否为空,并且我正在使用以下语法:
void renderSearch(Customer c){
System.out.println("search customer rendering>...");
try {
if(!c.equals(null)){
System.out.println("search customer found...");
}else{
System.out.println("search customer not found...");
}
} catch (Exception e) {
System.err.println ("search customer rendering error: "
+ e.getMessage()+"-"+e.getClass());
}
}
I get the following exception :
我收到以下异常:
search customer rendering error: null class java.lang.NullPointerException
搜索客户渲染错误:空类 java.lang.NullPointerException
I thought that I was considering this possibility with my if and else loop. Any help would be appreciated.
我认为我正在考虑使用 if 和 else 循环的这种可能性。任何帮助,将不胜感激。
采纳答案by Suvesh Pratapa
Try c != null in your if statement. You're not comparing the objects themselves, you're comparing their references.
在 if 语句中尝试 c != null 。您不是在比较对象本身,而是在比较它们的引用。
回答by Alex Martelli
Use c == null
, since you're comparing references, not objects.
使用c == null
,因为您比较的是引用,而不是对象。
回答by Midhat
Use c==null
使用 c==null
The equals method (usually) expects an argument of type customer, and may be calling some methods on the object. If that object is null you will get the NullPointerException.
equals 方法(通常)需要一个 customer 类型的参数,并且可能正在调用对象上的一些方法。如果该对象为空,您将获得 NullPointerException。
Also c might be null and c.equals call could be throwing the exception regardless of the object passed
此外 c 可能为 null 并且 c.equals 调用可能会抛出异常,无论传递的对象如何
回答by Greg Leaver
!c.equals(null)
That line is calling the equals method on c, and if c is null then you'll get that error because you can't call any methods on null. Instead you should be using
该行正在调用 c 上的 equals 方法,如果 c 为 null,那么您将收到该错误,因为您无法在 null 上调用任何方法。相反,你应该使用
c != null
回答by Nrj
Most likely Object c is null in this case.
在这种情况下,对象 c 很可能为空。
You might want to override the default implementation of equals for Customer in case you need to behave it differently.
您可能想要覆盖 Customer 的 equals 的默认实现,以防您需要对其进行不同的处理。
Also make sure passed object is not null before invoking the functions on it.
在调用它的函数之前,还要确保传递的对象不为空。
回答by shaik
if C object having null value then following statement used to compare null value:
如果 C 对象具有空值,则以下语句用于比较空值:
if (c.toString() == null) {
System.out.println("hello execute statement");
}
回答by José García
The reality is that when c is null, you are trying to do null.equals so this generates an exception. The correct way to do that comparison is "null".equals(c).
实际情况是,当 c 为 null 时,您正在尝试执行 null.equals,因此会产生异常。进行这种比较的正确方法是“null”.equals(c)。