Java - How do I compare two objects that might be empty?

I need to be able to compare two variables that can sometimes be null. If they are both zero, I still want it to be considered equal. Is there a suitable way to do this?

I tested it in NetBeans and looked at the documentation for .equals () and saw null references behave strangely.

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 a NullPointerException.

Am I working the way I want in this case, or was I just "lucky" here and came to the conclusion "true" for some other reason?

The NullPointerException also baffles me as I have always understood the equals method as reference equality. The documentation repeatedly mentions "non-null" objects, but why does this matter for reference comparison? Any clarification would be greatly appreciated.

+3


source to share


3 answers


The operator ==

checks if two variables have the same value. For object references, this means that the variables must refer to the same object (or both must be null

). Of course, the method equals()

requires that the variable it is called on is not null

. This behavior depends on the type of object being referenced (the actual object, not the declared type). The default (definable Object

) behavior is easy to use ==

.

To get the behavior you want, you can:

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

      



NOTE. In Java 7, you can use:

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

      

which does the same internally.

+9


source


You cannot call a method that is equal to zero. If you want to use saftly method you have to check for null value like



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

      

+1


source


a.equals(b)

returns a NullPointerException as it is literally

null.equals(...)

and null has no .equals (or any other method).

same thing with b.equals(a)

a == b

returns true because it is null == null

(obviously true). Therefore, for comparison you need to check a

and b

to a null value 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;

      

operator ?: for this

0


source







All Articles