Sarah Taylor Sarah Taylor - 7 months ago 30
Java Question

Java null.equals(object o)

I know it's not possible to call the equals method on a null object like that:

//NOT WORKING
String s1 = null;
String s2 = null;
if(s1.equals(s2))
{
System.out.println("NOT WORKING :'(");
}


But in my case I want to compare two objects from two database and these two objects can have attributes null...

So what is the method to compare two attributes, knowing that we are not sure that the value is null or filled.

This method is good or not ?

//WORKING
String s1 = "test";
String s2 = "test";
if(s1 == s2 || s1.equals(s2))
{
System.out.println("WORKING :)");
}

//WORKING
String s1 = null;
String s2 = null;
if(s1 == s2 || s1.equals(s2))
{
System.out.println("WORKING :)");
}


I'm not sure because in this case it's not working ... :

//NOT WORKING
String s1 = null;
String s2 = null;
if(s1.equals(s2)|| s1 == s2 )
{
System.out.println("NOT WORKING :'''(");
}

Answer

I generally use a static utility function that I wrote called equalsWithNulls to solve this issue:

class MyUtils {
  public static final boolean equalsWithNulls(Object a, Object b) {
    if (a==b) return true;
    if ((a==null)||(b==null)) return false;
    return a.equals(b);
  }
}

Usage:

if (MyUtils.equalsWithNulls(s1,s2)) {
  // do stuff
}

Advantages of this approach:

  • Wraps up the complexity of the full equality test in a single function call. I think this is much better than embedding a bunch of complex boolean tests in your code each time you do this. It's much less likely to lead to errors as a result.
  • Makes your code more descriptive and hence easier to read.
  • By explicitly mentioning the nulls in the method name, you convey to the reader that they should remember that one or both of the arguments might be null.
  • Does the (a==b) test first (an optimisation which avoids the need to call a.equals(b) in the fairly common case that a and b are non-null but refer to exactly the same object)
Comments