简体   繁体   中英

Checking if two objects are equals, null matching everything

Believe me or not, despite the plethora of questions asking about equality and null , I could not find an answer to this particular question:

Is there a standard method (or in a commonly used library) that compares two objects, and return true if they are equals or if one or more is null?

Example

I could write this code:

a == null || b == null || a.equals(b)

But it would be nice to simply encapsulate it in a EqualsUtils.equalsOrNull(a, b) . Easier to read and maintain.

Thing is, there is little point in writing my own if there is a commonly used one already that Jimmy will understand immediately when he gets to maintaining my code.

For this particular project, I can only use standard Java 7, or Apache Commons. Answers using other libraries (such as Guava and the like) are welcome for the sake of future readers, if they do not reference something "too obscure".

Niche answers for a and b of type String are welcome too, as it covers my use case.

there is little point in writing my own in there is a commonly used one already

This is not a commonly used pattern, it is illogical. Write your own if it fits your need.

But for other more conventional patterns use Guava , or apache commons .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM