简体   繁体   中英

Checking if two objects are equal even if they could be null

Sometimes, I see this:

if (a.equals(b)) do(something);

However, if a is null, a NullPointerException is thrown. Assuming when a==null and b==null or if just a==b that I would want to do(something) . What's the simplest way to do this check without getting an exception?

另一种写作方式。

if (a == null ? b == null : a.equals(b))
if( a==b || (a!=null && a.equals(b)) )

(The a==b handles the case when both are null.)


Also be aware of the Java 7 and above Object.equals method:

if(java.util.Object.equals(a, b))

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