101

To save some typing and clarify my code, is there a standard version of the following method?

public static boolean bothNullOrEqual(Object x, Object y) {
  return ( x == null ? y == null : x.equals(y) );
}
Chris Conway
  • 55,321
  • 43
  • 129
  • 155
  • 6
    Just my two cents. I would use: public static boolean bothNullOrEqual(Object x, Object y) { return ( x == y || ( x != null && x.equals(y) ) ); } IMHO, It's more readable for novice programmers. – m_vitaly Sep 05 '10 at 07:49
  • Can someone say where such a thing is useful ? – anjanb Oct 08 '08 at 21:43
  • 2
    It just allows you to skip null checks in your equals() method. – Michael Myers Oct 08 '08 at 21:47
  • Only if you only ever use the bothNullOrEqual function... what if you use equals directly in one place? – Neil Williams Oct 08 '08 at 22:13
  • It does seem strange that you'd want the same behaviour if two objects were equal OR were both NULL ... – Bobby Jack Oct 08 '08 at 22:16
  • 1
    If you are implementing a Collection, your .contains() method, when given "o" needs to test "if this collection contains at least one element e such that (o==null ? e==null : o.equals(e))." Similarly, your .remove() method has to remove such an element. – newacct Jul 09 '09 at 06:16
  • 1
    Another use case: compare a value to see if it has changed from it's previous value during a dirty check. – Relefant Nov 16 '13 at 23:48
  • You might want to update the selected answer to @Kdeveloper's Java 7 solution. – Marc M. May 03 '16 at 00:21

3 Answers3

195

With Java 7 you can now directly do a null safe equals:

Objects.equals(x, y)

(The Jakarta Commons library ObjectUtils.equals() has become obsolete with Java 7)

Community
  • 1
  • 1
Kdeveloper
  • 13,679
  • 11
  • 41
  • 49
23

if by some chance you are have access to the Jakarta Commons library there is ObjectUtils.equals() and lots of other useful functions.

EDIT: misread the question initially

Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
Matt
  • 2,226
  • 16
  • 18
8

If you are using <1.7 but have Guava available: Objects.equal(x, y)

Sam Berry
  • 7,394
  • 6
  • 40
  • 58