Monday, February 21, 2011

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) );
}
From stackoverflow
  • 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.

    Chris Conway : 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.
    Michael Myers : I think maybe he's talking about operator overloading?
    finnw : 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.
  • 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?).

  • 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

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

  • Can someone say where such a thing is useful ?

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

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

0 comments:

Post a Comment