简体   繁体   中英

java - How to compare two objects that might be null?

I need to be able to compare two variables, which might at some times be null. If they're both null, I still want it to be considered equal. Is there any appropriate way to do this?

I was testing it out in NetBeans, and looking at the documentation for .equals(), and saw that null references behave weirdly.

These are my examples and results:

Object a = null, b = null;
System.out.println(a == b);

returns true.

OR:

System.out.println(a.equals(b));

throws NullPointerException.

Does == work how I want it to in this case, or am I just 'getting lucky' here and it came to the conclusion 'true' for some other reason?

The NullPointerException is also confusing me, as I always understood Object's equals method to be a reference equality. The documentation repeatedly states 'non-null' Objects, but why would that matter for a reference comparison? Any clarification would be greatly appreciated.

The == operator tests whether two variables have identical value. For object references, this means that the variables must refer to the same object (or both variables must be null ). The equals() method, of course, requires that the variable on which it is invoked not be null . It's behavior depends on the type of object being referenced (on the actual object, not on the declared type). The default behavior (defined by Object ) is to simply use == .

To get the behavior you want, you can do:

System.out.println(a == null ? b == null : a.equals(b));

NOTE: as of Java 7, you can use:

System.out.println(java.util.Objects.equals(a, b));

which does the same thing internally.

a.equals(b) returns a NullPointerException because it's literally

null.equals(...)

and null doesn't have a .equals (or any other method).

same thing with b.equals(a)

a == b returns true because it's null == null (obviously true). So to compare you have to check a and b for null or something like...

if (a != null) 
   return a.equals(b);  // This works because a is not null.  `a.equals(null)` is valid.  
else if (b != null) 
   return b.equals(a);  // a is null, but b is not
else 
   return a == b;

the ?: operator is a bit more concise for this

You cannot invoke a method like equals on null value. If you want use a method saftly you must check null value like

if(a!=null)
    System.out.println(a.equals(b));
else
    System.out.println(a==b));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM