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?
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 .
7. == and != The comparison and not equal to operators are allowed with null in Java.
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 "!=
Java 7 offers java.util.Objects.equals.
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#
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With