Chris Conway
Chris Conway

Reputation: 55989

Is there a Java standard "both null or equal" static method?

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) );
}

Upvotes: 102

Views: 35852

Answers (3)

Sam Berry
Sam Berry

Reputation: 7844

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

Upvotes: 8

Matt
Matt

Reputation: 2224

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

Upvotes: 23

Kdeveloper
Kdeveloper

Reputation: 13819

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)

Upvotes: 195

Related Questions