Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

null

equals

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) ); } 
like image 564
Chris Conway Avatar asked Oct 08 '08 20:10

Chris Conway


People also ask

Is equals () method is a static method?

Objects provide a static Equals method, which can be used when there is a chance that one or both of the parameters can be null, other than that, it behaves identically to the virtual Object. Equals method. There is also a static ReferenceEquals method, which provides a guaranteed way to check for reference equality.

Can you call .equals on null Java?

Code Correctness: null Argument to equals()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 . (If the object is null , the program will throw a NullPointerException ).

Is it possible to override equals method in Java?

You can override the equals method on a record, if you want a behavior other than the default. But if you do override equals , be sure to override hashCode for consistent logic, as you would for a conventional Java class.

Does Java Set Use equal?

The equals() method of java. util. Set class is used to verify the equality of an Object with a Set and compare them. The method returns true if the size of both the sets are equal and both contain the same elements.


2 Answers

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)

like image 174
Kdeveloper Avatar answered Sep 22 '22 18:09

Kdeveloper


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

like image 35
Matt Avatar answered Sep 20 '22 18:09

Matt