Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent null check before equals

I find stuff like this rather annoying and ugly in equals methods:

if (field == null)
{
    if (other.field != null)
        return false;
}
else if ( ! field.equals(other.field))
    return false;

In C# I could've done this:

if( ! Object.Equals(field, other.field))
    return false;

Is there something similar in Java, or what is the preferred way to do this kind if thing?

like image 699
Svish Avatar asked Oct 25 '11 13:10

Svish


People also ask

Can you use == for null?

equals(null) will always be false. The program uses the equals() method to compare an object with null . This comparison will always return false, since the object is not null .

Can you do == null in Java?

7. == and != The comparison and not equal to operators are allowed with null in Java.

How do you check for equal null?

Use "==" to check a variable's value. A "==" is used to check that the two values on either side are equal. If you set a variable to null with "=" then checking that the variable is equal to null would return true. variableName == null; You can also use "!=


4 Answers

Java 7 offers java.util.Objects.equals.

like image 187
pholser Avatar answered Sep 28 '22 09:09

pholser


Use commons-lang:

org.apache.commons.lang.ObjectUtils.equals(Object object1, Object object2) 

Source code:

public static boolean equals(Object object1, Object object2) {     if (object1 == object2) {         return true;     }     if ((object1 == null) || (object2 == null)) {         return false;     }     return object1.equals(object2); } 

From Apache

http://commons.apache.org/lang/

That's about equivalent to what you do in C#

like image 33
Lukas Eder Avatar answered Sep 28 '22 10:09

Lukas Eder


Guava equal which does this :

public static boolean equal(@Nullable Object a, @Nullable Object b) {
    return a == b || (a != null && a.equals(b));
  }

or null object pattern

Guava also has the somewhat related comparison chain and a load of other goodies.

like image 41
NimChimpsky Avatar answered Sep 28 '22 10:09

NimChimpsky


I would write it this way:

return field != null && other.field != null && field.equals(other.field);

which is not as elegant as the C# code line, but much shorter then the if tree you posted.

like image 21
HefferWolf Avatar answered Sep 28 '22 11:09

HefferWolf