tags:

views:

728

answers:

6

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

I know it can be done in VB - http://www.csidata.com/custserv/onlinehelp/VBSdocs/vbs428.htm, it's the EQV operator.

It can be done in Perl, and C++ would view (X==Y) fine if both are NULL.

Based on this page from the Java tutorial from Sun, http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html, it appears to not be possible.

warren
In what sense is it "not possible"? It's quite possible: the above method is perfectly legal. The question is whether it's implemented in the JDK.
Chris Conway
I think maybe he's talking about operator overloading?
Michael Myers
Your C++ example is not equivalent to the Java version. X and Y could be non-null and point to objects with equal content, and (X==Y) would return false.
finnw
+1  A: 

No. I've seen people suggesting putting a similar method in a utility class, but it isn't in the standard library (the Object class seems like a good place, but who am I to suggest it?).

Michael Myers
+3  A: 

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

Matt
A: 

No. I've written my own on every project I've been on I think.

Alex Miller
+1  A: 

Can someone say where such a thing is useful ?

anjanb
It just allows you to skip null checks in your equals() method.
Michael Myers
Only if you only ever use the bothNullOrEqual function... what if you use equals directly in one place?
Neil Williams
It does seem strange that you'd want the same behaviour if two objects were equal OR were both NULL ...
Bobby Jack
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
A: 

I have this method.

For the sake of saving character calories, its named eq.

Adrian